UNPKG

1.4 kBJavaScriptView Raw
1/**
2 * Transaction Output Map
3 * ======================
4 *
5 * A map from a transaction hash and output number to that particular output.
6 * Note that the map is from the transaction *hash*, which is the value that
7 * occurs in the blockchain, not the id, which is the reverse of the hash. The
8 * TxOutMap is necessary when signing a transction to get the script and value
9 * of that output which is plugged into the sighash algorithm.
10 */
11'use strict'
12
13import { Struct } from './struct'
14import { TxOut } from './tx-out'
15
16class TxOutMap extends Struct {
17 constructor (map = new Map()) {
18 super({ map })
19 }
20
21 toJSON () {
22 const json = {}
23 this.map.forEach((txOut, label) => {
24 json[label] = txOut.toHex()
25 })
26 return json
27 }
28
29 fromJSON (json) {
30 Object.keys(json).forEach(label => {
31 this.map.set(label, TxOut.fromHex(json[label]))
32 })
33 return this
34 }
35
36 set (txHashBuf, txOutNum, txOut) {
37 const label = txHashBuf.toString('hex') + ':' + txOutNum
38 this.map.set(label, txOut)
39 return this
40 }
41
42 get (txHashBuf, txOutNum) {
43 const label = txHashBuf.toString('hex') + ':' + txOutNum
44 return this.map.get(label)
45 }
46
47 setTx (tx) {
48 const txhashhex = tx.hash().toString('hex')
49 tx.txOuts.forEach((txOut, index) => {
50 const label = txhashhex + ':' + index
51 this.map.set(label, txOut)
52 })
53 return this
54 }
55}
56
57export { TxOutMap }