@bsv/sdk 1.1.23 → 1.1.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/package.json +1 -1
- package/dist/cjs/src/primitives/Curve.js +7 -7
- package/dist/cjs/src/primitives/Curve.js.map +1 -1
- package/dist/cjs/src/primitives/ECDSA.js +394 -71
- package/dist/cjs/src/primitives/ECDSA.js.map +1 -1
- package/dist/cjs/src/primitives/Point.js +103 -23
- package/dist/cjs/src/primitives/Point.js.map +1 -1
- package/dist/cjs/src/primitives/TransactionSignature.js +4 -3
- package/dist/cjs/src/primitives/TransactionSignature.js.map +1 -1
- package/dist/cjs/src/primitives/utils.js +14 -15
- package/dist/cjs/src/primitives/utils.js.map +1 -1
- package/dist/cjs/src/script/Spend.js +4 -4
- package/dist/cjs/src/script/Spend.js.map +1 -1
- package/dist/cjs/src/transaction/Transaction.js +79 -65
- package/dist/cjs/src/transaction/Transaction.js.map +1 -1
- package/dist/cjs/tsconfig.cjs.tsbuildinfo +1 -1
- package/dist/esm/src/primitives/Curve.js +7 -7
- package/dist/esm/src/primitives/Curve.js.map +1 -1
- package/dist/esm/src/primitives/ECDSA.js +394 -71
- package/dist/esm/src/primitives/ECDSA.js.map +1 -1
- package/dist/esm/src/primitives/Point.js +103 -23
- package/dist/esm/src/primitives/Point.js.map +1 -1
- package/dist/esm/src/primitives/TransactionSignature.js +4 -3
- package/dist/esm/src/primitives/TransactionSignature.js.map +1 -1
- package/dist/esm/src/primitives/utils.js +14 -15
- package/dist/esm/src/primitives/utils.js.map +1 -1
- package/dist/esm/src/script/Spend.js +4 -4
- package/dist/esm/src/script/Spend.js.map +1 -1
- package/dist/esm/src/transaction/Transaction.js +79 -65
- package/dist/esm/src/transaction/Transaction.js.map +1 -1
- package/dist/esm/tsconfig.esm.tsbuildinfo +1 -1
- package/dist/types/src/primitives/ECDSA.d.ts.map +1 -1
- package/dist/types/src/primitives/Point.d.ts +5 -0
- package/dist/types/src/primitives/Point.d.ts.map +1 -1
- package/dist/types/src/primitives/TransactionSignature.d.ts.map +1 -1
- package/dist/types/src/primitives/utils.d.ts.map +1 -1
- package/dist/types/src/transaction/Transaction.d.ts.map +1 -1
- package/dist/types/src/transaction/TransactionInput.d.ts +1 -1
- package/dist/types/src/transaction/TransactionInput.d.ts.map +1 -1
- package/dist/types/tsconfig.types.tsbuildinfo +1 -1
- package/docs/primitives.md +4 -3
- package/docs/transaction.md +1 -1
- package/package.json +1 -1
- package/src/primitives/Curve.ts +7 -7
- package/src/primitives/ECDSA.ts +485 -75
- package/src/primitives/Point.ts +110 -25
- package/src/primitives/TransactionSignature.ts +4 -3
- package/src/primitives/utils.ts +15 -11
- package/src/script/Spend.ts +4 -4
- package/src/transaction/Transaction.ts +93 -68
- package/src/transaction/TransactionInput.ts +1 -1
- package/src/transaction/__tests/Transaction.benchmarks.test.ts +222 -0
package/src/primitives/Point.ts
CHANGED
|
@@ -17,6 +17,10 @@ import ReductionContext from './ReductionContext.js'
|
|
|
17
17
|
* @property inf - Flag to record if the point is at infinity in the Elliptic Curve.
|
|
18
18
|
*/
|
|
19
19
|
export default class Point extends BasePoint {
|
|
20
|
+
private static readonly red: any = new ReductionContext('k256')
|
|
21
|
+
private static readonly a: BigNumber = new BigNumber(0).toRed(Point.red)
|
|
22
|
+
private static readonly b: BigNumber = new BigNumber(7).toRed(Point.red)
|
|
23
|
+
private static readonly zero: BigNumber = new BigNumber(0).toRed(Point.red)
|
|
20
24
|
x: BigNumber | null
|
|
21
25
|
y: BigNumber | null
|
|
22
26
|
inf: boolean
|
|
@@ -59,7 +63,7 @@ export default class Point extends BasePoint {
|
|
|
59
63
|
|
|
60
64
|
return res
|
|
61
65
|
} else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&
|
|
62
|
-
|
|
66
|
+
bytes.length - 1 === len) {
|
|
63
67
|
return Point.fromX(bytes.slice(1, 1 + len), bytes[0] === 0x03)
|
|
64
68
|
}
|
|
65
69
|
throw new Error('Unknown point format')
|
|
@@ -87,6 +91,13 @@ export default class Point extends BasePoint {
|
|
|
87
91
|
return Point.fromDER(bytes)
|
|
88
92
|
}
|
|
89
93
|
|
|
94
|
+
static redSqrtOptimized (y2: BigNumber): BigNumber {
|
|
95
|
+
const red = Point.red
|
|
96
|
+
const p = red.m // The modulus
|
|
97
|
+
const exponent = p.addn(1).iushrn(2) // (p + 1) / 4
|
|
98
|
+
return y2.redPow(exponent)
|
|
99
|
+
}
|
|
100
|
+
|
|
90
101
|
/**
|
|
91
102
|
* Generates a point from an x coordinate and a boolean indicating whether the corresponding
|
|
92
103
|
* y coordinate is odd.
|
|
@@ -102,34 +113,108 @@ export default class Point extends BasePoint {
|
|
|
102
113
|
* const xCoordinate = new BigNumber('10');
|
|
103
114
|
* const point = Point.fromX(xCoordinate, true);
|
|
104
115
|
*/
|
|
105
|
-
|
|
106
116
|
static fromX (x: BigNumber | number | number[] | string, odd: boolean): Point {
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
117
|
+
if (typeof BigInt === 'function') {
|
|
118
|
+
function mod (a: bigint, n: bigint): bigint {
|
|
119
|
+
return ((a % n) + n) % n
|
|
120
|
+
}
|
|
121
|
+
function modPow (base: bigint, exponent: bigint, modulus: bigint): bigint {
|
|
122
|
+
let result = BigInt(1)
|
|
123
|
+
base = mod(base, modulus)
|
|
124
|
+
while (exponent > BigInt(0)) {
|
|
125
|
+
if ((exponent & BigInt(1)) === BigInt(1)) {
|
|
126
|
+
result = mod(result * base, modulus)
|
|
127
|
+
}
|
|
128
|
+
exponent >>= BigInt(1)
|
|
129
|
+
base = mod(base * base, modulus)
|
|
130
|
+
}
|
|
131
|
+
return result
|
|
132
|
+
}
|
|
133
|
+
function sqrtMod (a: bigint, p: bigint): bigint | null {
|
|
134
|
+
const exponent = (p + BigInt(1)) >> BigInt(2) // Precomputed exponent
|
|
135
|
+
const sqrtCandidate = modPow(a, exponent, p)
|
|
136
|
+
if (mod(sqrtCandidate * sqrtCandidate, p) === mod(a, p)) {
|
|
137
|
+
return sqrtCandidate
|
|
138
|
+
} else {
|
|
139
|
+
// No square root exists
|
|
140
|
+
return null
|
|
141
|
+
}
|
|
142
|
+
}
|
|
118
143
|
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
144
|
+
// Curve parameters for secp256k1
|
|
145
|
+
const p = BigInt(
|
|
146
|
+
'0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F'
|
|
147
|
+
)
|
|
148
|
+
const a = BigInt(0)
|
|
149
|
+
const b = BigInt(7)
|
|
150
|
+
|
|
151
|
+
// Convert x to BigInt
|
|
152
|
+
let xBigInt: bigint
|
|
153
|
+
if (x instanceof BigNumber) {
|
|
154
|
+
xBigInt = BigInt('0x' + x.toString(16))
|
|
155
|
+
} else if (typeof x === 'string') {
|
|
156
|
+
xBigInt = BigInt('0x' + x)
|
|
157
|
+
} else if (Array.isArray(x)) {
|
|
158
|
+
xBigInt = BigInt(
|
|
159
|
+
'0x' +
|
|
160
|
+
Buffer.from(x).toString('hex').padStart(64, '0')
|
|
161
|
+
)
|
|
162
|
+
} else if (typeof x === 'number') {
|
|
163
|
+
xBigInt = BigInt(x)
|
|
164
|
+
} else {
|
|
165
|
+
throw new Error('Invalid x-coordinate type')
|
|
166
|
+
}
|
|
124
167
|
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
const isOdd = y.fromRed().isOdd()
|
|
128
|
-
if ((odd && !isOdd) || (!odd && isOdd)) {
|
|
129
|
-
y = y.redNeg()
|
|
130
|
-
}
|
|
168
|
+
// Ensure x is within field range
|
|
169
|
+
xBigInt = mod(xBigInt, p)
|
|
131
170
|
|
|
132
|
-
|
|
171
|
+
// Compute y^2 = x^3 + a x + b mod p
|
|
172
|
+
const y2 = mod(modPow(xBigInt, BigInt(3), p) + b, p)
|
|
173
|
+
|
|
174
|
+
// Compute modular square root y = sqrt(y2) mod p
|
|
175
|
+
let y = sqrtMod(y2, p)
|
|
176
|
+
|
|
177
|
+
if (y === null) {
|
|
178
|
+
throw new Error('Invalid point')
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// Adjust y to match the oddness
|
|
182
|
+
const isYOdd = (y % BigInt(2)) === BigInt(1)
|
|
183
|
+
if ((odd && !isYOdd) || (!odd && isYOdd)) {
|
|
184
|
+
y = p - y
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// Convert x and y to BigNumber
|
|
188
|
+
const xBN = new BigNumber(xBigInt.toString(16), 16)
|
|
189
|
+
const yBN = new BigNumber(y.toString(16), 16)
|
|
190
|
+
return new Point(xBN, yBN)
|
|
191
|
+
} else {
|
|
192
|
+
const red = new ReductionContext('k256')
|
|
193
|
+
const a = new BigNumber(0).toRed(red)
|
|
194
|
+
const b = new BigNumber(7).toRed(red)
|
|
195
|
+
const zero = new BigNumber(0).toRed(red)
|
|
196
|
+
if (!BigNumber.isBN(x)) {
|
|
197
|
+
x = new BigNumber(x as number, 16)
|
|
198
|
+
}
|
|
199
|
+
x = x as BigNumber
|
|
200
|
+
if (x.red == null) {
|
|
201
|
+
x = x.toRed(red)
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const y2 = x.redSqr().redMul(x).redIAdd(x.redMul(a)).redIAdd(b)
|
|
205
|
+
let y = y2.redSqrt()
|
|
206
|
+
if (y.redSqr().redSub(y2).cmp(zero) !== 0) {
|
|
207
|
+
throw new Error('invalid point')
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// XXX Is there any way to tell if the number is odd without converting it
|
|
211
|
+
// to non-red form?
|
|
212
|
+
const isOdd = y.fromRed().isOdd()
|
|
213
|
+
if ((odd && !isOdd) || (!odd && isOdd)) {
|
|
214
|
+
y = y.redNeg()
|
|
215
|
+
}
|
|
216
|
+
return new Point(x, y)
|
|
217
|
+
}
|
|
133
218
|
}
|
|
134
219
|
|
|
135
220
|
/**
|
|
@@ -40,7 +40,7 @@ export default class TransactionSignature extends Signature {
|
|
|
40
40
|
const writer = new Writer()
|
|
41
41
|
for (const input of inputs) {
|
|
42
42
|
if (typeof input.sourceTXID === 'undefined') {
|
|
43
|
-
writer.
|
|
43
|
+
writer.write(input.sourceTransaction.hash() as number[])
|
|
44
44
|
} else {
|
|
45
45
|
writer.writeReverse(toArray(input.sourceTXID, 'hex'))
|
|
46
46
|
}
|
|
@@ -122,8 +122,9 @@ export default class TransactionSignature extends Signature {
|
|
|
122
122
|
writer.writeUInt32LE(params.sourceOutputIndex)
|
|
123
123
|
|
|
124
124
|
// scriptCode of the input (serialized as scripts inside CTxOuts)
|
|
125
|
-
|
|
126
|
-
writer.
|
|
125
|
+
const subscriptBin = params.subscript.toBinary()
|
|
126
|
+
writer.writeVarIntNum(subscriptBin.length)
|
|
127
|
+
writer.write(subscriptBin)
|
|
127
128
|
|
|
128
129
|
// value of the output spent by this input (8-byte little endian)
|
|
129
130
|
writer.writeUInt64LE(params.sourceSatoshis)
|
package/src/primitives/utils.ts
CHANGED
|
@@ -320,9 +320,13 @@ export class Writer {
|
|
|
320
320
|
}
|
|
321
321
|
|
|
322
322
|
toArray (): number[] {
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
323
|
+
const totalLength = this.getLength()
|
|
324
|
+
const ret = new Array(totalLength)
|
|
325
|
+
let offset = 0
|
|
326
|
+
for (const buf of this.bufs) {
|
|
327
|
+
for (let i = 0; i < buf.length; i++) {
|
|
328
|
+
ret[offset++] = buf[i]
|
|
329
|
+
}
|
|
326
330
|
}
|
|
327
331
|
return ret
|
|
328
332
|
}
|
|
@@ -515,18 +519,18 @@ export class Reader {
|
|
|
515
519
|
}
|
|
516
520
|
|
|
517
521
|
public read (len = this.bin.length): number[] {
|
|
518
|
-
const
|
|
519
|
-
|
|
520
|
-
|
|
522
|
+
const start = this.pos
|
|
523
|
+
const end = this.pos + len
|
|
524
|
+
this.pos = end
|
|
525
|
+
return this.bin.slice(start, end)
|
|
521
526
|
}
|
|
522
527
|
|
|
523
528
|
public readReverse (len = this.bin.length): number[] {
|
|
524
|
-
const
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
for (let i = 0; i < buf2.length; i++) {
|
|
528
|
-
buf2[i] = bin[bin.length - 1 - i]
|
|
529
|
+
const buf2 = new Array(len)
|
|
530
|
+
for (let i = 0; i < len; i++) {
|
|
531
|
+
buf2[i] = this.bin[this.pos + len - 1 - i]
|
|
529
532
|
}
|
|
533
|
+
this.pos += len
|
|
530
534
|
return buf2
|
|
531
535
|
}
|
|
532
536
|
|
package/src/script/Spend.ts
CHANGED
|
@@ -207,9 +207,9 @@ export default class Spend {
|
|
|
207
207
|
}
|
|
208
208
|
|
|
209
209
|
const padDataToSize = (buf: number[], len: number): number[] => {
|
|
210
|
-
|
|
210
|
+
const b = buf
|
|
211
211
|
while (b.length < len) {
|
|
212
|
-
b
|
|
212
|
+
b.unshift(0)
|
|
213
213
|
}
|
|
214
214
|
return b
|
|
215
215
|
}
|
|
@@ -785,7 +785,7 @@ export default class Spend {
|
|
|
785
785
|
shifted = bn1.ushrn(n)
|
|
786
786
|
}
|
|
787
787
|
const bufShifted = padDataToSize(
|
|
788
|
-
|
|
788
|
+
shifted.toArray().slice(buf1.length * -1),
|
|
789
789
|
buf1.length
|
|
790
790
|
)
|
|
791
791
|
this.stack.push(bufShifted)
|
|
@@ -1016,7 +1016,7 @@ export default class Spend {
|
|
|
1016
1016
|
|
|
1017
1017
|
try {
|
|
1018
1018
|
sig = TransactionSignature.fromChecksigFormat(bufSig)
|
|
1019
|
-
pubkey = PublicKey.
|
|
1019
|
+
pubkey = PublicKey.fromDER(bufPubkey)
|
|
1020
1020
|
fSuccess = verifySignature(sig, pubkey, subscript)
|
|
1021
1021
|
} catch (e) {
|
|
1022
1022
|
// invalid sig or pubkey
|
|
@@ -593,9 +593,8 @@ export default class Transaction {
|
|
|
593
593
|
}
|
|
594
594
|
if (enc === 'hex') {
|
|
595
595
|
return toHex(hash)
|
|
596
|
-
} else {
|
|
597
|
-
return hash
|
|
598
596
|
}
|
|
597
|
+
return hash
|
|
599
598
|
}
|
|
600
599
|
|
|
601
600
|
/**
|
|
@@ -635,84 +634,110 @@ export default class Transaction {
|
|
|
635
634
|
*
|
|
636
635
|
* @example tx.verify(new WhatsOnChain(), new SatoshisPerKilobyte(1))
|
|
637
636
|
*/
|
|
638
|
-
async verify (
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
return true
|
|
651
|
-
}
|
|
637
|
+
async verify (
|
|
638
|
+
chainTracker: ChainTracker | 'scripts only' = defaultChainTracker(),
|
|
639
|
+
feeModel?: FeeModel
|
|
640
|
+
): Promise<boolean> {
|
|
641
|
+
const verifiedTxids = new Set<string>()
|
|
642
|
+
const txQueue: Transaction[] = [this]
|
|
643
|
+
|
|
644
|
+
while (txQueue.length > 0) {
|
|
645
|
+
const tx = txQueue.shift()
|
|
646
|
+
const txid = tx.id('hex')
|
|
647
|
+
if (verifiedTxids.has(txid)) {
|
|
648
|
+
continue
|
|
652
649
|
}
|
|
653
|
-
}
|
|
654
|
-
|
|
655
|
-
if (typeof feeModel !== 'undefined') {
|
|
656
|
-
const cpTx = Transaction.fromHexEF(this.toHexEF())
|
|
657
|
-
delete cpTx.outputs[0].satoshis
|
|
658
|
-
cpTx.outputs[0].change = true
|
|
659
|
-
await cpTx.fee(feeModel)
|
|
660
|
-
if (this.getFee() < cpTx.getFee()) throw new Error(`Verification failed because the transaction ${this.id('hex')} has an insufficient fee and has not been mined.`)
|
|
661
|
-
}
|
|
662
650
|
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
651
|
+
// If the transaction has a valid merkle path, verification is complete.
|
|
652
|
+
if (typeof tx.merklePath === 'object') {
|
|
653
|
+
if (chainTracker === 'scripts only') {
|
|
654
|
+
verifiedTxids.add(txid)
|
|
655
|
+
continue
|
|
656
|
+
} else {
|
|
657
|
+
const proofValid = await tx.merklePath.verify(
|
|
658
|
+
txid,
|
|
659
|
+
chainTracker
|
|
660
|
+
)
|
|
661
|
+
// If the proof is valid, no need to verify inputs.
|
|
662
|
+
if (proofValid) {
|
|
663
|
+
verifiedTxids.add(txid)
|
|
664
|
+
continue
|
|
665
|
+
}
|
|
666
|
+
}
|
|
673
667
|
}
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
668
|
+
|
|
669
|
+
// Verify fee if feeModel is provided
|
|
670
|
+
if (typeof feeModel !== 'undefined') {
|
|
671
|
+
const cpTx = Transaction.fromEF(tx.toEF())
|
|
672
|
+
delete cpTx.outputs[0].satoshis
|
|
673
|
+
cpTx.outputs[0].change = true
|
|
674
|
+
await cpTx.fee(feeModel)
|
|
675
|
+
if (tx.getFee() < cpTx.getFee()) {
|
|
676
|
+
throw new Error(`Verification failed because the transaction ${txid} has an insufficient fee and has not been mined.`)
|
|
677
|
+
}
|
|
679
678
|
}
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
679
|
+
|
|
680
|
+
// Verify each input transaction and evaluate the spend events.
|
|
681
|
+
// Also, keep a total of the input amounts for later.
|
|
682
|
+
let inputTotal = 0
|
|
683
|
+
for (let i = 0; i < tx.inputs.length; i++) {
|
|
684
|
+
const input = tx.inputs[i]
|
|
685
|
+
if (typeof input.sourceTransaction !== 'object') {
|
|
686
|
+
throw new Error(`Verification failed because the input at index ${i} of transaction ${txid} is missing an associated source transaction. This source transaction is required for transaction verification because there is no merkle proof for the transaction spending a UTXO it contains.`)
|
|
687
|
+
}
|
|
688
|
+
if (typeof input.unlockingScript !== 'object') {
|
|
689
|
+
throw new Error(`Verification failed because the input at index ${i} of transaction ${txid} is missing an associated unlocking script. This script is required for transaction verification because there is no merkle proof for the transaction spending the UTXO.`)
|
|
690
|
+
}
|
|
691
|
+
const sourceOutput = input.sourceTransaction.outputs[input.sourceOutputIndex]
|
|
692
|
+
inputTotal += sourceOutput.satoshis
|
|
693
|
+
|
|
694
|
+
const sourceTxid = input.sourceTransaction.id('hex')
|
|
695
|
+
if (!verifiedTxids.has(sourceTxid)) {
|
|
696
|
+
txQueue.push(input.sourceTransaction)
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
const otherInputs = tx.inputs.filter((_, idx) => idx !== i)
|
|
700
|
+
if (typeof input.sourceTXID === 'undefined') {
|
|
701
|
+
input.sourceTXID = sourceTxid
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
const spend = new Spend({
|
|
705
|
+
sourceTXID: input.sourceTXID,
|
|
706
|
+
sourceOutputIndex: input.sourceOutputIndex,
|
|
707
|
+
lockingScript: sourceOutput.lockingScript,
|
|
708
|
+
sourceSatoshis: sourceOutput.satoshis,
|
|
709
|
+
transactionVersion: tx.version,
|
|
710
|
+
otherInputs,
|
|
711
|
+
unlockingScript: input.unlockingScript,
|
|
712
|
+
inputSequence: input.sequence,
|
|
713
|
+
inputIndex: i,
|
|
714
|
+
outputs: tx.outputs,
|
|
715
|
+
lockTime: tx.lockTime
|
|
716
|
+
})
|
|
717
|
+
const spendValid = spend.validate()
|
|
718
|
+
|
|
719
|
+
if (!spendValid) {
|
|
720
|
+
return false
|
|
721
|
+
}
|
|
684
722
|
}
|
|
685
723
|
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
inputSequence: input.sequence,
|
|
695
|
-
inputIndex: i,
|
|
696
|
-
outputs: this.outputs,
|
|
697
|
-
lockTime: this.lockTime
|
|
698
|
-
})
|
|
699
|
-
const spendValid = spend.validate()
|
|
724
|
+
// Total the outputs to ensure they don't amount to more than the inputs
|
|
725
|
+
let outputTotal = 0
|
|
726
|
+
for (const out of tx.outputs) {
|
|
727
|
+
if (typeof out.satoshis !== 'number') {
|
|
728
|
+
throw new Error('Every output must have a defined amount during transaction verification.')
|
|
729
|
+
}
|
|
730
|
+
outputTotal += out.satoshis
|
|
731
|
+
}
|
|
700
732
|
|
|
701
|
-
if (
|
|
733
|
+
if (outputTotal > inputTotal) {
|
|
702
734
|
return false
|
|
703
735
|
}
|
|
704
|
-
}
|
|
705
736
|
|
|
706
|
-
|
|
707
|
-
let outputTotal = 0
|
|
708
|
-
for (const out of this.outputs) {
|
|
709
|
-
if (typeof out.satoshis !== 'number') {
|
|
710
|
-
throw new Error('Every output must have a defined amount during transaction verification.')
|
|
711
|
-
}
|
|
712
|
-
outputTotal += out.satoshis
|
|
737
|
+
verifiedTxids.add(txid)
|
|
713
738
|
}
|
|
714
739
|
|
|
715
|
-
return
|
|
740
|
+
return true
|
|
716
741
|
}
|
|
717
742
|
|
|
718
743
|
/**
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
// __tests__/transaction.benchmark.test.ts
|
|
2
|
+
|
|
3
|
+
import Transaction from '../../../dist/cjs/src/transaction/Transaction'
|
|
4
|
+
import PrivateKey from '../../../dist/cjs/src/primitives/PrivateKey'
|
|
5
|
+
import { hash160 } from '../../../dist/cjs/src/primitives/Hash'
|
|
6
|
+
import P2PKH from '../../../dist/cjs/src/script/templates/P2PKH'
|
|
7
|
+
import { jest } from '@jest/globals'
|
|
8
|
+
|
|
9
|
+
jest.setTimeout(60000) // Increase timeout for benchmarking tests if necessary
|
|
10
|
+
|
|
11
|
+
// Helper function to measure execution time
|
|
12
|
+
async function measureTime(fn: () => Promise<void>): Promise<number> {
|
|
13
|
+
const start = process.hrtime()
|
|
14
|
+
await fn()
|
|
15
|
+
const diff = process.hrtime(start)
|
|
16
|
+
const timeInMs = diff[0] * 1000 + diff[1] / 1e6
|
|
17
|
+
return timeInMs
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
describe('Transaction Verification Benchmark', () => {
|
|
21
|
+
const privateKey = new PrivateKey(1)
|
|
22
|
+
const publicKey = privateKey.toPublicKey()
|
|
23
|
+
const publicKeyHash = hash160(publicKey.toDER())
|
|
24
|
+
const p2pkh = new P2PKH()
|
|
25
|
+
|
|
26
|
+
it('verifies a transaction with a deep input chain', async () => {
|
|
27
|
+
// Create a deep chain of transactions (e.g., depth of 100)
|
|
28
|
+
const depth = 100
|
|
29
|
+
let tx = new Transaction()
|
|
30
|
+
tx.addOutput({
|
|
31
|
+
lockingScript: p2pkh.lock(publicKeyHash),
|
|
32
|
+
satoshis: 100000
|
|
33
|
+
})
|
|
34
|
+
tx.merklePath = {
|
|
35
|
+
// Mock merkle path verification
|
|
36
|
+
blockHeight: 0,
|
|
37
|
+
merkleRoot: '',
|
|
38
|
+
hashes: [],
|
|
39
|
+
verify: async () => true,
|
|
40
|
+
toBinary: () => [],
|
|
41
|
+
computeRoot: () => ''
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Build the chain
|
|
45
|
+
for (let i = 0; i < depth; i++) {
|
|
46
|
+
const newTx = new Transaction()
|
|
47
|
+
newTx.addInput({
|
|
48
|
+
sourceTransaction: tx,
|
|
49
|
+
sourceOutputIndex: 0,
|
|
50
|
+
unlockingScriptTemplate: p2pkh.unlock(privateKey),
|
|
51
|
+
sequence: 0xffffffff
|
|
52
|
+
})
|
|
53
|
+
newTx.addOutput({
|
|
54
|
+
lockingScript: p2pkh.lock(publicKeyHash),
|
|
55
|
+
satoshis: 100000 - 1000 * (i + 1)
|
|
56
|
+
})
|
|
57
|
+
await newTx.sign()
|
|
58
|
+
tx = newTx
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Measure verification time
|
|
62
|
+
const timeTaken = await measureTime(async () => {
|
|
63
|
+
const verified = await tx.verify('scripts only')
|
|
64
|
+
expect(verified).toBe(true)
|
|
65
|
+
})
|
|
66
|
+
console.log(`Verification time for deep chain of depth ${depth}: ${timeTaken.toFixed(2)} ms`)
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
it('verifies a transaction with a wide input set', async () => {
|
|
70
|
+
// Create a transaction with many inputs (e.g., 100 inputs)
|
|
71
|
+
const inputCount = 100
|
|
72
|
+
const sourceTxs = []
|
|
73
|
+
|
|
74
|
+
// Create source transactions
|
|
75
|
+
for (let i = 0; i < inputCount; i++) {
|
|
76
|
+
const sourceTx = new Transaction()
|
|
77
|
+
sourceTx.addOutput({
|
|
78
|
+
lockingScript: p2pkh.lock(publicKeyHash),
|
|
79
|
+
satoshis: 1000
|
|
80
|
+
})
|
|
81
|
+
sourceTx.merklePath = {
|
|
82
|
+
blockHeight: 0,
|
|
83
|
+
merkleRoot: '',
|
|
84
|
+
hashes: [],
|
|
85
|
+
verify: async () => true,
|
|
86
|
+
toBinary: () => [],
|
|
87
|
+
computeRoot: () => ''
|
|
88
|
+
}
|
|
89
|
+
sourceTxs.push(sourceTx)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Create transaction with many inputs
|
|
93
|
+
const tx = new Transaction()
|
|
94
|
+
for (let i = 0; i < inputCount; i++) {
|
|
95
|
+
tx.addInput({
|
|
96
|
+
sourceTransaction: sourceTxs[i],
|
|
97
|
+
sourceOutputIndex: 0,
|
|
98
|
+
unlockingScriptTemplate: p2pkh.unlock(privateKey),
|
|
99
|
+
sequence: 0xffffffff
|
|
100
|
+
})
|
|
101
|
+
}
|
|
102
|
+
tx.addOutput({
|
|
103
|
+
lockingScript: p2pkh.lock(publicKeyHash),
|
|
104
|
+
satoshis: inputCount * 1000 - 1000
|
|
105
|
+
})
|
|
106
|
+
await tx.sign()
|
|
107
|
+
|
|
108
|
+
// Measure verification time
|
|
109
|
+
const timeTaken = await measureTime(async () => {
|
|
110
|
+
const verified = await tx.verify('scripts only')
|
|
111
|
+
expect(verified).toBe(true)
|
|
112
|
+
})
|
|
113
|
+
console.log(`Verification time for wide transaction with ${inputCount} inputs: ${timeTaken.toFixed(2)} ms`)
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
it('verifies a large transaction with many inputs and outputs', async () => {
|
|
117
|
+
const inputCount = 50
|
|
118
|
+
const outputCount = 50
|
|
119
|
+
const sourceTxs = []
|
|
120
|
+
|
|
121
|
+
// Create source transactions
|
|
122
|
+
for (let i = 0; i < inputCount; i++) {
|
|
123
|
+
const sourceTx = new Transaction()
|
|
124
|
+
sourceTx.addOutput({
|
|
125
|
+
lockingScript: p2pkh.lock(publicKeyHash),
|
|
126
|
+
satoshis: 2000
|
|
127
|
+
})
|
|
128
|
+
sourceTx.merklePath = {
|
|
129
|
+
blockHeight: 0,
|
|
130
|
+
merkleRoot: '',
|
|
131
|
+
hashes: [],
|
|
132
|
+
verify: async () => true,
|
|
133
|
+
toBinary: () => [],
|
|
134
|
+
computeRoot: () => ''
|
|
135
|
+
}
|
|
136
|
+
sourceTxs.push(sourceTx)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Create transaction with many inputs and outputs
|
|
140
|
+
const tx = new Transaction()
|
|
141
|
+
for (let i = 0; i < inputCount; i++) {
|
|
142
|
+
tx.addInput({
|
|
143
|
+
sourceTransaction: sourceTxs[i],
|
|
144
|
+
sourceOutputIndex: 0,
|
|
145
|
+
unlockingScriptTemplate: p2pkh.unlock(privateKey),
|
|
146
|
+
sequence: 0xffffffff
|
|
147
|
+
})
|
|
148
|
+
}
|
|
149
|
+
for (let i = 0; i < outputCount; i++) {
|
|
150
|
+
tx.addOutput({
|
|
151
|
+
lockingScript: p2pkh.lock(publicKeyHash),
|
|
152
|
+
satoshis: 1000
|
|
153
|
+
})
|
|
154
|
+
}
|
|
155
|
+
await tx.sign()
|
|
156
|
+
|
|
157
|
+
// Measure verification time
|
|
158
|
+
const timeTaken = await measureTime(async () => {
|
|
159
|
+
const verified = await tx.verify('scripts only')
|
|
160
|
+
expect(verified).toBe(true)
|
|
161
|
+
})
|
|
162
|
+
console.log(`Verification time for large transaction with ${inputCount} inputs and ${outputCount} outputs: ${timeTaken.toFixed(2)} ms`)
|
|
163
|
+
})
|
|
164
|
+
|
|
165
|
+
it('verifies a transaction with nested inputs (complex graph)', async () => {
|
|
166
|
+
// Create a transaction graph where inputs come from transactions with multiple inputs
|
|
167
|
+
const depth = 5
|
|
168
|
+
const fanOut = 3
|
|
169
|
+
let txs = []
|
|
170
|
+
|
|
171
|
+
// Create base transactions
|
|
172
|
+
for (let i = 0; i < fanOut; i++) {
|
|
173
|
+
const baseTx = new Transaction()
|
|
174
|
+
baseTx.addOutput({
|
|
175
|
+
lockingScript: p2pkh.lock(publicKeyHash),
|
|
176
|
+
satoshis: 100000
|
|
177
|
+
})
|
|
178
|
+
baseTx.merklePath = {
|
|
179
|
+
blockHeight: 0,
|
|
180
|
+
merkleRoot: '',
|
|
181
|
+
hashes: [],
|
|
182
|
+
verify: async () => true,
|
|
183
|
+
toBinary: () => [],
|
|
184
|
+
computeRoot: () => ''
|
|
185
|
+
}
|
|
186
|
+
txs.push(baseTx)
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// Build the graph
|
|
190
|
+
for (let d = 0; d < depth; d++) {
|
|
191
|
+
const newTxs = []
|
|
192
|
+
for (const tx of txs) {
|
|
193
|
+
const newTx = new Transaction()
|
|
194
|
+
for (let i = 0; i < fanOut; i++) {
|
|
195
|
+
newTx.addInput({
|
|
196
|
+
sourceTransaction: tx,
|
|
197
|
+
sourceOutputIndex: 0,
|
|
198
|
+
unlockingScriptTemplate: p2pkh.unlock(privateKey),
|
|
199
|
+
sequence: 0xffffffff
|
|
200
|
+
})
|
|
201
|
+
}
|
|
202
|
+
newTx.addOutput({
|
|
203
|
+
lockingScript: p2pkh.lock(publicKeyHash),
|
|
204
|
+
satoshis: tx.outputs[0].satoshis - 1000 * fanOut
|
|
205
|
+
})
|
|
206
|
+
await newTx.sign()
|
|
207
|
+
newTxs.push(newTx)
|
|
208
|
+
}
|
|
209
|
+
txs = newTxs
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// Take the last transaction for verification
|
|
213
|
+
const finalTx = txs[0]
|
|
214
|
+
|
|
215
|
+
// Measure verification time
|
|
216
|
+
const timeTaken = await measureTime(async () => {
|
|
217
|
+
const verified = await finalTx.verify('scripts only')
|
|
218
|
+
expect(verified).toBe(true)
|
|
219
|
+
})
|
|
220
|
+
console.log(`Verification time for nested inputs with depth ${depth} and fan-out ${fanOut}: ${timeTaken.toFixed(2)} ms`)
|
|
221
|
+
})
|
|
222
|
+
})
|