Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 | /*! * http.js - http server for bmultisig * Copyright (c) 2018, The Bcoin Developers (MIT License). * https://github.com/bcoin-org/bmultisig */ 'use strict'; const assert = require('bsert'); const bcoin = require('bcoin'); const {Outpoint, Script, Address, Network} = bcoin; const HDPublicKey = bcoin.hd.HDPublicKey; const Validator = require('bval'); const Logger = require('blgr'); const {base58} = require('bstring'); const sha256 = require('bcrypto/lib/sha256'); const random = require('bcrypto/lib/random'); const {safeEqual} = require('bcrypto/lib/safe'); const {Server} = require('bweb'); const MultisigDB = require('./multisigdb'); const Cosigner = require('./primitives/cosigner'); const Proposal = require('./primitives/proposal'); const RouteList = require('./utils/routelist'); const {WalletDetails} = require('./export'); const {FORCE} = Proposal.status; /** * Multisig HTTP server * @alias module:multisig.HTTP * @extends {Server} * @property {MultisigHTTPOptions} options * @property {MultisigDB} msdb * @property {bcoin.Network} network * @property {Logger} logger * @property {bcoin.wallet.HTTP} whttp * @property {RouteList} notauthRoutes - skip authentication * @property {RouteList} proxyRoutes - proxy requests to the bwallet */ class MultisigHTTP extends Server { /** * Create an http server. * @constructor * @param {MultisigHTTPOptions} options * @param {MultisigDB} options.msdb * @param {Logger} options.logger * @param {bcoin.Network} options.network * @param {bcoin.wallet.HTTP} options.whttp * @param {String} options.version */ constructor(options) { super(new MultisigHTTPOptions(options)); this.msdb = this.options.msdb; this.network = this.options.network; this.logger = this.options.logger.context('multisig-http'); this.whttp = this.options.whttp; this.noauthRoutes = new RouteList(); this.proxyRoutes = new RouteList(); this.init(); } /* * Initialize http server. */ init() { this.on('request', (req, res) => { this.logger.debug('Request for method=%s path=/multisig%s (%s).', req.method, req.pathname, req.socket.remoteAddress); }); this.setupNoAuthRoutes(); this.setupProxyRoutes(); this.initRouter(); this.initSockets(); } /* * Skip authentication for these routes */ setupNoAuthRoutes() { // create wallet this.noauthRoutes.put('/:id'); // join wallet this.noauthRoutes.post('/:id/join'); // admin paths this.noauthRoutes.get('/'); this.noauthRoutes.del('/:id'); } /* * Proxy these routes */ setupProxyRoutes() { this.proxyRoutes.post('/:id/zap'); // abandon transactions this.proxyRoutes.del('/:id/tx/:hash'); this.proxyRoutes.get('/:id/block'); this.proxyRoutes.get('/:id/block/:height'); this.proxyRoutes.get('/:id/key/:address'); this.proxyRoutes.post('/:id/address'); this.proxyRoutes.post('/:id/change'); this.proxyRoutes.post('/:id/nested'); this.proxyRoutes.get('/:id/balance'); this.proxyRoutes.get('/:id/coin'); this.proxyRoutes.get('/:id/coin/:hash/:index'); this.proxyRoutes.get('/:id/tx/history'); this.proxyRoutes.get('/:id/tx/unconfirmed'); this.proxyRoutes.get('/:id/tx/range'); this.proxyRoutes.get('/:id/tx/last'); this.proxyRoutes.get('/:id/tx/:hash'); this.proxyRoutes.post('/:id/resend'); } /* * Admin authentication */ async checkAdminHook(req, res) { if (!this.options.walletAuth) { req.admin = true; return; } const valid = Validator.fromRequest(req); const token = valid.buf('token'); if (token && safeEqual(token, this.options.adminToken)) { req.admin = true; return; } } /* * grab wallet and attach to request */ async getWalletHook(req, res) { // contains - :id if (!req.params.id) return; // ignore - PUT /multisig/:id if (req.path.length === 1 && req.method === 'PUT') return; const id = req.params.id; if (!id) { res.json(400); return; } const mswallet = await this.msdb.getWallet(id); if (!mswallet) { res.json(404); return; } req.mswallet = mswallet; req.wallet = mswallet.wallet; } /* * Authenticate user with cosignerToken */ async cosignerAuth(req, res) { if (req.admin) return; if (this.noauthRoutes.has(req)) return; const valid = Validator.fromRequest(req); const mswallet = req.mswallet; const cosignerToken = valid.buf('token'); if (!cosignerToken || !mswallet) error(403, 'Authentication error.'); const cosigner = mswallet.auth(cosignerToken); req.cosigner = cosigner; } async proxyRequest(req, res) { assert(this.whttp, 'Can not proxy without parent wallet http'); if (!this.proxyRoutes.has(req)) return; // PROXY Routes don't go through normal hooks // get wallet await this.getWalletHook(req, res); if (res.sent) return; // authenticate.. await this.cosignerAuth(req, res); // We already did authentication with cosignerToken // wallet.HTTP does not need to check walletToken req.admin = true; // replace /multisig with /wallet for // wallet.HTTP to handle it. const url = '/wallet' + req.url; req.navigate(url); // because we only use one account // all account related stuff can use `default` account req.query.account = 'default'; const route = await this.whttp.routes.handle(req, res); if (!route) res.json(404); } /* * Initialize routes. */ initRouter() { if (this.options.cors) this.use(this.cors()); if (!this.options.noAuth) { this.use(this.basicAuth({ hash: sha256.digest, password: this.options.apiKey, realm: 'wallet' })); } this.use(this.bodyParser({ type: 'json' })); // check if token is for admin this.use(this.checkAdminHook.bind(this)); // proxy request to wallet this.use(this.proxyRequest.bind(this)); this.use(this.router()); this.error((err, req, res) => { const code = err.statusCode || 500; res.json(code, { error: { type: err.type, code: err.code, message: err.message } }); }); // load wallet this.hook(this.getWalletHook.bind(this)); // authenticate cosigner this.hook(this.cosignerAuth.bind(this)); // List wallets (Admin Only) this.get('/', async (req, res) => { if (!req.admin) { res.json(403); return; } const wallets = await this.msdb.getWallets(); res.json(200, { wallets }); }); // Get wallet information this.get('/:id', async (req, res) => { const balance = await req.wallet.getBalance(); const stats = await req.mswallet.getStats(); res.json(200, req.mswallet.getJSON({ balance, stats })); }); // Create multisig wallet this.put('/:id', async (req, res) => { const valid = Validator.fromRequest(req); const id = valid.str('id'); const joinSignature = valid.buf('joinSignature'); const joinPubKey = valid.buf('joinPubKey'); // wallet options const walletOptions = { id: id, m: valid.u32('m'), n: valid.u32('n'), witness: valid.bool('witness', true), joinPubKey: joinPubKey }; // cosigner options const cosignerVal = new Validator(valid.obj('cosigner'), false); const name = cosignerVal.str('name'); const purpose = cosignerVal.u32('purpose'); const fingerPrint = cosignerVal.u32('fingerPrint'); const data = cosignerVal.buf('data'); const accountKey = cosignerVal.str('accountKey'); const key = HDPublicKey.fromBase58(accountKey, this.network); const keyProof = cosignerVal.buf('accountKeyProof'); // multisig auth/validation options const token = cosignerVal.buf('token'); const authPubKey = cosignerVal.buf('authPubKey'); const cosigner = Cosigner.fromOptions({ name, purpose, fingerPrint, data, authPubKey, joinSignature, token, key }); if (keyProof) { const validKeyProof = cosigner.verifyProof( keyProof, id, this.network ); enforce(validKeyProof, 'accountKeyProof is not valid.'); } const mswallet = await this.msdb.create(walletOptions, cosigner); const stats = await mswallet.getStats(); res.json(200, mswallet.getJSON({ stats, cosignerIndex: 0 })); }); // Removes wallet from WDB and MSDB unindexes all info this.del('/:id', async (req, res) => { if (!req.admin) { res.json(403); return; } const removed = await req.mswallet.remove(); res.json(200, { success: removed }); }); // Get locked coins in TXDB this.get('/:id/locked', async (req, res) => { const valid = Validator.fromRequest(req); const proposalOnly = valid.bool('proposalOnly', false); const locked = await req.mswallet.getLocked(proposalOnly); const result = []; for (const outpoint of locked) result.push(outpoint.toJSON()); res.json(200, result); }); // Lock coin this.put('/:id/locked/:hash/:index', async (req, res) => { const valid = Validator.fromRequest(req); const hash = valid.brhash('hash'); const index = valid.u32('index'); enforce(hash, 'Hash is required.'); enforce(index != null, 'Index is required.'); const outpoint = new Outpoint(hash, index); req.mswallet.lockCoinTXDB(outpoint); res.json(200, { success: true }); }); // Unlock coin. this.del('/:id/locked/:hash/:index', async (req, res) => { const valid = Validator.fromRequest(req); const hash = valid.brhash('hash'); const index = valid.u32('index'); const force = valid.bool('force', false); enforce(hash, 'Hash is required.'); enforce(index != null, 'Index is required.'); const outpoint = new Outpoint(hash, index); if (force && req.admin) { await req.mswallet.forceUnlockCoin(outpoint); res.json(200, { success: true }); return; } await req.mswallet.unlockCoin(outpoint); res.json(200, { success: true }); }); // Export wallet. this.get('/:id/export', async (req, res) => { if (!req.admin) { res.json(403); return; } const id = req.mswallet.id; const info = await this.msdb.export(id); const json = info.getJSON(this.network); res.json(200, json); }); // Import wallet. this.post('/import', async (req, res) => { if (!req.admin) { res.json(403); return; } const valid = Validator.fromRequest(req); const id = valid.str('id'); const options = valid.obj('importOptions'); const importDetails = WalletDetails.fromJSON(options); const mswallet = await this.msdb.import(id, importDetails); res.json(200, mswallet.getJSON({ cosignerIndex: 0 })); }); // Join multisig wallet this.post('/:id/join', async (req, res) => { const valid = Validator.fromRequest(req); const joinSignature = valid.buf('joinSignature'); // cosigner options const cosignerVal = new Validator(valid.obj('cosigner'), false); const name = cosignerVal.str('name'); const purpose = cosignerVal.u32('purpose'); const fingerPrint = cosignerVal.u32('fingerPrint'); const data = cosignerVal.buf('data'); const accountKey = cosignerVal.str('accountKey'); const key = HDPublicKey.fromBase58(accountKey, this.network); const keyProof = cosignerVal.buf('accountKeyProof'); // multisig auth/validation options const token = cosignerVal.buf('token'); const authPubKey = cosignerVal.buf('authPubKey'); const cosigner = Cosigner.fromOptions({ name, purpose, fingerPrint, data, authPubKey, joinSignature, token, key }); if (keyProof) { const validKeyProof = cosigner.verifyProof( keyProof, req.mswallet.id, this.network ); enforce(validKeyProof, 'accountKeyProof is not valid.'); } const joined = await req.mswallet.join(cosigner, key); const cosignerIndex = joined.cosigners.length - 1; res.json(200, joined.getJSON({ cosignerIndex })); }); // List accounts (compatibility). this.get('/:id/account', (req, res) => { res.json(200, ['default']); }); // Get account (compatibility). this.get('/:id/account/:account', async (req, res) => { const valid = Validator.fromRequest(req); const acct = valid.str('account', 'default'); if (acct !== 'default') { res.json(404); return; } const account = await req.mswallet.getAccount(); const balance = await req.wallet.getBalance(); res.json(200, account.getJSON(balance)); }); // Set new token for cosigner this.put('/:id/token', async (req, res) => { enforce(req.cosigner, 'Cosigner not found.'); const valid = Validator.fromRequest(req); const token = valid.buf('newToken'); enforce(token.length === 32, 'newToken must be 32 bytes.'); const cosigner = await req.mswallet.setToken(req.cosigner, token); res.json(200, cosigner.getJSON(true, this.network)); }); // Create tx this.post('/:id/create', async (req, res) => { const valid = Validator.fromRequest(req); const options = parseTXOptions(valid, this.network); const tx = await req.mswallet.createTX(options); res.json(200, tx.getJSON(this.network)); }); // Get list of proposals. // TODO: Add limits. this.get('/:id/proposal', async (req, res) => { const valid = Validator.fromRequest(req); const pending = valid.bool('pending', true); let proposals; if (pending) { proposals = await req.mswallet.getPendingProposals(); } else { proposals = await req.mswallet.getProposals(); } return res.json(200, { proposals: proposals.map((p) => { return p.getJSON(null, req.mswallet.cosigners, this.network); }) }); }); // Create proposal. this.post('/:id/proposal', async (req, res) => { enforce(req.cosigner, 'Cosigner not found.'); const requestValid = Validator.fromRequest(req); const signature = requestValid.buf('signature'); const options = requestValid.obj('proposal'); const valid = new Validator(options, false); const txValid = new Validator(valid.obj('txoptions'), false); const txoptions = parseTXOptions(txValid, this.network); const memo = valid.str('memo'); const timestamp = valid.u64('timestamp'); enforce(memo, 'Memo not found.'); enforce(timestamp, 'Timestamp not found.'); const [proposal, tx] = await req.mswallet.createProposal( options, req.cosigner, txoptions, signature ); enforce(proposal, 'Could not create proposal.'); res.json(200, proposal.getJSON(tx, req.mswallet.cosigners, this.network)); }); // Get proposal info this.get('/:id/proposal/:pid', async (req, res) => { const valid = Validator.fromRequest(req); const pid = valid.u32('pid'); const getTX = valid.bool('tx', true); const proposal = await req.mswallet.getProposal(pid); if (!proposal) { res.json(404); return; } let tx = null; if (getTX) tx = await req.mswallet.getProposalTX(pid); const cosigners = req.mswallet.cosigners; res.json(200, proposal.getJSON(tx, cosigners, this.network)); }); // Get proposal mtx // TODO: Add option for returning previous transactions. this.get('/:id/proposal/:pid/tx', async (req, res) => { const valid = Validator.fromRequest(req); const pid = valid.u32('pid'); const getPaths = valid.bool('paths', false); const getScripts = valid.bool('scripts', false); const getTXs = valid.bool('txs', false); let paths, txs, rings, scripts; const mtx = await req.mswallet.getProposalMTX(pid); if (!mtx) { res.json(404); return; } if (getPaths) paths = await req.mswallet.getInputPaths(mtx); if (getScripts && rings) scripts = rings.map(r => r.script); if (getScripts && !rings) { const rings = await req.mswallet.deriveInputs(mtx, paths); scripts = rings.map(r => r.script); } if (getTXs) { txs = []; for (const {prevout} of mtx.inputs) { const {hash} = prevout; const record = await req.wallet.getTX(hash); txs.push(record.tx); } } res.json(200, { tx: mtx.getJSON(this.network), txs: txs ? txs.map(t => t.toRaw().toString('hex')) : null, paths: paths ? paths.map((p) => { if (!p) return null; return { branch: p.branch, index: p.index, receive: p.branch === 0, change: p.branch === 1, nested: p.branch === 2 }; }) : null, scripts: scripts ? scripts.map(s => s.toRaw().toString('hex')) : null }); }); // Approve proposal this.post('/:id/proposal/:pid/approve', async (req, res) => { const valid = Validator.fromRequest(req); const pid = valid.u32('pid'); const hexSigs = valid.array('signatures', []); const broadcast = valid.bool('broadcast', true); enforce(req.cosigner, 'Cosigner not found.'); enforce(hexSigs.length, 'Could not find signatures'); const sigs = hexSigs.map((sig) => { if (!sig) return null; return Buffer.from(sig, 'hex'); }); enforce(sigs && sigs.length > 0, 'Signatures not found.'); const proposal = await req.mswallet.approveProposal( pid, req.cosigner, sigs ); if (!proposal) { res.json(404); return; } let broadcasted = false, tx, err; if (proposal.isApproved() && broadcast) { try { tx = await req.mswallet.sendProposal(pid); assert(tx, 'Could not broadcast approved proposal.'); broadcasted = true; } catch (e) { err = e; this.logger.debug(`Failed to broadcast ${e.message}`); } } res.json(200, { broadcasted, broadcastError: err ? err.message : null, proposal: proposal.getJSON(tx) }); }); // Reject proposal this.post('/:id/proposal/:pid/reject', async (req, res) => { const valid = Validator.fromRequest(req); const pid = valid.u32('pid'); const force = valid.bool('force', false); const signature = valid.buf('signature'); if (force && req.admin) { const proposal = await req.mswallet.forceRejectProposal(pid, FORCE); if (!proposal) { res.json(404); return; } res.json(200, proposal.toJSON()); return; } if (force) { res.json(403); return; } enforce(req.cosigner, 'Cosigner not found.'); const proposal = await req.mswallet.rejectProposal( pid, req.cosigner, signature ); if (!proposal) { res.json(404); return; } res.json(200, proposal.toJSON()); }); // Get proposal by coin (Admin or Cosigner) this.get('/:id/proposal/coin/:hash/:index', async (req, res) => { const valid = Validator.fromRequest(req); const hash = valid.brhash('hash'); const index = valid.u32('index'); enforce(hash, 'Hash is required.'); enforce(index != null, 'Index is required.'); const outpoint = new Outpoint(hash, index); const proposal = await req.mswallet.getProposalByOutpoint(outpoint); if (!proposal) { res.json(404); return; } res.json(200, proposal.toJSON()); }); // Send proposal tx this.post('/:id/proposal/:pid/send', async (req, res) => { const valid = Validator.fromRequest(req); const pid = valid.u32('pid'); const tx = await req.mswallet.sendProposal(pid); if (!tx) { res.json(404); return; } res.json(200, tx.toJSON()); }); } /* * Initialize websockets. */ initSockets() { const handleEvent = (event, wallet, json) => { const name = `w:${wallet.id}`; if (!this.channel(name) && !this.channel('w:*')) return; if (this.channel(name)) this.to(name, event, wallet.id, json); if (this.channel('w:*')) this.to('w:*', event, wallet.id, json); }; this.msdb.on('join', (wallet, cosigner) => { const json = cosigner.getJSON(false, this.network); handleEvent('join', wallet, json); }); this.msdb.on('proposal created', (wallet, proposal, tx) => { const json = proposal.getJSON(tx, wallet.cosigners, this.network); handleEvent('proposal created', wallet, json); }); this.msdb.on('proposal rejected', (wallet, proposal, cosigner) => { const json = { proposal: proposal.getJSON(), cosigner: cosigner ? cosigner.getJSON(false, this.network) : null }; handleEvent('proposal rejected', wallet, json); }); this.msdb.on('proposal approved', (wallet, proposal, cosigner, tx) => { const json = { proposal: proposal.getJSON(tx), cosigner: cosigner.getJSON(false, this.network) }; handleEvent('proposal approved', wallet, json); }); } handleSocket(socket) { socket.hook('ms-join', async (...args) => { const valid = new Validator(args); const id = valid.str(0, ''); const token = valid.buf(1); if (!id) throw new Error('Invalid parameter.'); if (!this.options.walletAuth) { socket.join('admin'); } else if (token) { if (safeEqual(token, this.options.adminToken)) socket.join('admin'); } if (socket.channel('admin') || !this.options.walletAuth) { socket.join(`w:${id}`); return null; } if (id === '*') throw new Error('Bad token.'); if (!token) throw new Error('Invalid parameter.'); const mswallet = await this.msdb.getWallet(id); if (!mswallet) throw new Error('Wallet does not exist.'); try { mswallet.auth(token); } catch (e) { this.logger.info(`Wallet auth failure for ${id}: ${e.message}`); throw new Error('Bad token.'); } this.logger.info(`Successful wallet auth for ${id}.`); socket.join(`w:${id}`); return null; }); } } /** * Multisig HTTP Options. * @property {MultisigDB} msdb * @property {bcoin.Network} network * @property {blgr.Logger} logger * @property {MultisigDB} msdb */ class MultisigHTTPOptions { constructor (options) { this.network = Network.primary; this.logger = Logger.global; this.msdb = null; this.whttp = null; this.version = '0.0.0'; this.apiKey = base58.encode(random.randomBytes(20)); this.apiHash = sha256.digest(Buffer.from(this.apiKey, 'ascii')); this.adminToken = random.randomBytes(32); this.serviceHash = this.apiHash; this.noAuth = false; this.walletAuth = false; this.cors = false; this.fromOptions(options); } fromOptions(options) { assert(options, 'MultisigHTTP Server requires options'); assert(options.msdb instanceof MultisigDB, 'MultiHTTP Server requires MultisigDB'); this.msdb = options.msdb; this.logger = options.msdb.logger; this.network = options.msdb.network; if (options.logger != null) { assert(typeof options.logger === 'object', 'MultiHTTP Server requires correct logger' ); this.logger = options.logger; } if (options.version != null) { assert(typeof options.version === 'string'); this.version = options.version; } if (options.apiKey != null) { assert(typeof options.apiKey === 'string', 'API key must be a string.'); assert(options.apiKey.length <= 255, 'API key must be under 255 bytes.'); this.apiKey = options.apiKey; this.apiHash = sha256.digest(Buffer.from(this.apiKey, 'ascii')); } if (options.whttp != null) { assert(typeof options.whttp === 'object', 'Incorrect wallet http' ); this.whttp = options.whttp; } if (options.adminToken != null) { if (typeof options.adminToken === 'string') { assert(options.adminToken.length === 64, 'Admin token must be a 32 byte hex string.'); const token = Buffer.from(options.adminToken, 'hex'); assert(token.length === 32, 'Admin token must be a 32 byte hex string.'); this.adminToken = token; } else { assert(Buffer.isBuffer(options.adminToken), 'Admin token must be a hex string or buffer.'); assert(options.adminToken.length === 32, 'Admin token must be 32 bytes.'); this.adminToken = options.adminToken; } } if (options.noAuth != null) { assert(typeof options.noAuth === 'boolean'); this.noAuth = options.noAuth; } if (options.walletAuth != null) { assert(typeof options.walletAuth === 'boolean'); this.walletAuth = options.walletAuth; } if (options.cors != null) { assert(typeof options.cors === 'boolean'); this.cors = options.cors; } } } /* * Helpers */ /** * Parse transaction options. * @ignore * @param {Validator} valid * @param {Network} network * @returns {Object} */ function parseTXOptions(valid, network) { const outputs = valid.array('outputs', []); const options = { rate: valid.u64('rate'), blocks: valid.u32('blocks'), maxFee: valid.u64('maxFee'), selection: valid.str('selection'), smart: valid.bool('smart'), sort: valid.bool('sort'), subtractFee: valid.bool('subtractFee'), subtractIndex: valid.i32('subtractIndex'), depth: valid.u32(['confirmations', 'depth']), outputs: [] }; for (const output of outputs) { const valid = new Validator(output); let addr = valid.str('address'); let script = valid.buf('script'); if (addr) addr = Address.fromString(addr, network); if (script) script = Script.fromRaw(script); options.outputs.push({ address: addr, script: script, value: valid.u64('value') }); } return options; } function error(statusCode, msg) { const err = new Error(msg); err.statusCode = statusCode; throw err; } function enforce(value, msg) { if (!value) error(400, msg); } /* * Expose */ module.exports = MultisigHTTP; |