@bsv/sdk 1.2.9 → 1.2.11

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.
@@ -5254,7 +5254,8 @@ create a corresponding public key and derive a shared secret from a public key.
5254
5254
  ```ts
5255
5255
  export default class PrivateKey extends BigNumber {
5256
5256
  static fromRandom(): PrivateKey
5257
- static fromString(str: string, base: number | "hex"): PrivateKey
5257
+ static fromString(str: string, base: number | "hex" = "hex"): PrivateKey
5258
+ static fromHex(str: string): PrivateKey
5258
5259
  static fromWif(wif: string, prefixLength: number = 1): PrivateKey
5259
5260
  constructor(number: BigNumber | number | string | number[] = 0, base: number | "be" | "le" | "hex" = 10, endian: "be" | "le" = "be", modN: "apply" | "nocheck" | "error" = "apply")
5260
5261
  checkInField(): {
@@ -5267,6 +5268,8 @@ export default class PrivateKey extends BigNumber {
5267
5268
  toPublicKey(): PublicKey
5268
5269
  toWif(prefix: number[] = [128]): string
5269
5270
  toAddress(prefix: number[] | string = [0]): string
5271
+ toHex(): string
5272
+ toString(base: number | "hex" = "hex", padding: number = 64): string
5270
5273
  deriveSharedSecret(key: PublicKey): Point
5271
5274
  deriveChild(publicKey: PublicKey, invoiceNumber: string): PrivateKey
5272
5275
  toKeyShares(threshold: number, totalShares: number): KeyShares
@@ -5276,7 +5279,7 @@ export default class PrivateKey extends BigNumber {
5276
5279
  }
5277
5280
  ```
5278
5281
 
5279
- See also: [BigNumber](#class-bignumber), [KeyShares](#class-keyshares), [Point](#class-point), [PublicKey](#class-publickey), [Signature](#class-signature), [sign](#variable-sign), [verify](#variable-verify)
5282
+ See also: [BigNumber](#class-bignumber), [KeyShares](#class-keyshares), [Point](#class-point), [PublicKey](#class-publickey), [Signature](#class-signature), [sign](#variable-sign), [toHex](#variable-tohex), [verify](#variable-verify)
5280
5283
 
5281
5284
  <details>
5282
5285
 
@@ -5394,6 +5397,28 @@ const share2 = 'Cm5fuUc39X5xgdedao8Pr1kvCSm8Gk7Cfenc7xUKcfLX.2juyK9BxCWn2DiY5JUA
5394
5397
  const recoveredKey = PrivateKey.fromBackupShares([share1, share2])
5395
5398
  ```
5396
5399
 
5400
+ #### Method fromHex
5401
+
5402
+ Generates a private key from a hexadecimal string.
5403
+
5404
+ ```ts
5405
+ static fromHex(str: string): PrivateKey
5406
+ ```
5407
+ See also: [PrivateKey](#class-privatekey)
5408
+
5409
+ Returns
5410
+
5411
+ The generated Private Key instance.
5412
+
5413
+ Argument Details
5414
+
5415
+ + **str**
5416
+ + The hexadecimal string representing the private key. The string must represent a valid private key in big-endian format.
5417
+
5418
+ Throws
5419
+
5420
+ If the string is not a valid hexadecimal or represents an invalid private key.
5421
+
5397
5422
  #### Method fromKeyShares
5398
5423
 
5399
5424
  Combines shares to reconstruct the private key.
@@ -5438,7 +5463,7 @@ const privateKey = PrivateKey.fromRandom();
5438
5463
  Generates a private key from a string.
5439
5464
 
5440
5465
  ```ts
5441
- static fromString(str: string, base: number | "hex"): PrivateKey
5466
+ static fromString(str: string, base: number | "hex" = "hex"): PrivateKey
5442
5467
  ```
5443
5468
  See also: [PrivateKey](#class-privatekey)
5444
5469
 
@@ -5562,6 +5587,30 @@ Argument Details
5562
5587
  + **totalShares**
5563
5588
  + The number of shares to generate for distribution.
5564
5589
 
5590
+ #### Method toHex
5591
+
5592
+ Converts this PrivateKey to a hexadecimal string.
5593
+
5594
+ ```ts
5595
+ toHex(): string
5596
+ ```
5597
+
5598
+ Returns
5599
+
5600
+ Returns a string representing the hexadecimal value of this BigNumber.
5601
+
5602
+ Argument Details
5603
+
5604
+ + **length**
5605
+ + The minimum length of the hex string
5606
+
5607
+ Example
5608
+
5609
+ ```ts
5610
+ const bigNumber = new BigNumber(255);
5611
+ const hex = bigNumber.toHex();
5612
+ ```
5613
+
5565
5614
  #### Method toKeyShares
5566
5615
 
5567
5616
  Splits the private key into shares using Shamir's Secret Sharing Scheme.
@@ -5613,6 +5662,27 @@ const privateKey = PrivateKey.fromRandom();
5613
5662
  const publicKey = privateKey.toPublicKey();
5614
5663
  ```
5615
5664
 
5665
+ #### Method toString
5666
+
5667
+ function toString() { [native code] }
5668
+
5669
+ Converts this PrivateKey to a string representation.
5670
+
5671
+ ```ts
5672
+ toString(base: number | "hex" = "hex", padding: number = 64): string
5673
+ ```
5674
+
5675
+ Returns
5676
+
5677
+ A string representation of the PrivateKey in the specified base, padded to the specified length.
5678
+
5679
+ Argument Details
5680
+
5681
+ + **base**
5682
+ + The base for representing the number. Default is hexadecimal ('hex').
5683
+ + **padding**
5684
+ + The minimum number of digits for the output string. Default is 64, ensuring a 256-bit representation in hexadecimal.
5685
+
5616
5686
  #### Method toWif
5617
5687
 
5618
5688
  Converts the private key to a Wallet Import Format (WIF) string.
@@ -592,6 +592,7 @@ export class Beef {
592
592
  constructor(version?: BeefVersion)
593
593
  get magic(): number
594
594
  findTxid(txid: string): BeefTx | undefined
595
+ makeTxidOnly(txid: string): BeefTx | undefined
595
596
  findBump(txid: string): MerklePath | undefined
596
597
  findTransactionForSigning(txid: string): Transaction | undefined
597
598
  findAtomicTransaction(txid: string): Transaction | undefined
@@ -779,6 +780,23 @@ Argument Details
779
780
  + **allowTxidOnly**
780
781
  + optional. If true, transaction txid only is assumed valid
781
782
 
783
+ #### Method makeTxidOnly
784
+
785
+ Replaces `BeefTx` for this txid with txidOnly.
786
+
787
+ Replacement is done so that a `clone()` can be
788
+ updated by this method without affecting the
789
+ original.
790
+
791
+ ```ts
792
+ makeTxidOnly(txid: string): BeefTx | undefined
793
+ ```
794
+ See also: [BeefTx](#class-beeftx)
795
+
796
+ Returns
797
+
798
+ undefined if txid is unknown.
799
+
782
800
  #### Method mergeBump
783
801
 
784
802
  Merge a MerklePath that is assumed to be fully valid.
@@ -847,7 +865,7 @@ Argument Details
847
865
  #### Method sortTxs
848
866
 
849
867
  Sort the `txs` by input txid dependency order:
850
- - Oldest Tx Anchored by Path
868
+ - Oldest Tx Anchored by Path or txid only
851
869
  - Newer Txs depending on Older parents
852
870
  - Newest Tx
853
871
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bsv/sdk",
3
- "version": "1.2.9",
3
+ "version": "1.2.11",
4
4
  "type": "module",
5
5
  "description": "BSV Blockchain Software Development Kit",
6
6
  "main": "dist/cjs/mod.js",
@@ -93,8 +93,21 @@ export default class PrivateKey extends BigNumber {
93
93
  * @returns The generated Private Key.
94
94
  * @throws Will throw an error if the string is not valid.
95
95
  **/
96
- static fromString (str: string, base: number | 'hex'): PrivateKey {
97
- return new PrivateKey(BigNumber.fromString(str, base).toArray())
96
+ static fromString (str: string, base: number | 'hex' = 'hex'): PrivateKey {
97
+ return new PrivateKey(super.fromString(str, base).toArray())
98
+ }
99
+
100
+ /**
101
+ * Generates a private key from a hexadecimal string.
102
+ *
103
+ * @method fromHex
104
+ * @static
105
+ * @param {string} str - The hexadecimal string representing the private key. The string must represent a valid private key in big-endian format.
106
+ * @returns {PrivateKey} The generated Private Key instance.
107
+ * @throws {Error} If the string is not a valid hexadecimal or represents an invalid private key.
108
+ **/
109
+ static fromHex (str: string): PrivateKey {
110
+ return new PrivateKey(super.fromHex(str, 'big'))
98
111
  }
99
112
 
100
113
  /**
@@ -274,6 +287,34 @@ export default class PrivateKey extends BigNumber {
274
287
  return this.toPublicKey().toAddress(prefix)
275
288
  }
276
289
 
290
+ /**
291
+ * Converts this PrivateKey to a hexadecimal string.
292
+ *
293
+ * @method toHex
294
+ * @param length - The minimum length of the hex string
295
+ * @returns Returns a string representing the hexadecimal value of this BigNumber.
296
+ *
297
+ * @example
298
+ * const bigNumber = new BigNumber(255);
299
+ * const hex = bigNumber.toHex();
300
+ */
301
+ toHex (): string {
302
+ return super.toHex(32)
303
+ }
304
+
305
+ /**
306
+ * Converts this PrivateKey to a string representation.
307
+ *
308
+ * @method toString
309
+ * @param {number | 'hex'} [base='hex'] - The base for representing the number. Default is hexadecimal ('hex').
310
+ * @param {number} [padding=64] - The minimum number of digits for the output string. Default is 64, ensuring a 256-bit representation in hexadecimal.
311
+ * @returns {string} A string representation of the PrivateKey in the specified base, padded to the specified length.
312
+ *
313
+ **/
314
+ toString (base: number | 'hex' = 'hex', padding: number = 64): string {
315
+ return super.toString(base, padding)
316
+ }
317
+
277
318
  /**
278
319
  * Derives a shared secret from the public key.
279
320
  *
@@ -1,17 +1,97 @@
1
1
  import PublicKey from '../../../dist/cjs/src/primitives/PublicKey'
2
2
  import PrivateKey from '../../../dist/cjs/src/primitives/PrivateKey'
3
3
  import BRC42Private from './BRC42.private.vectors'
4
+ import Curve from '../../../dist/cjs/src/primitives/Curve'
5
+ import BigNumber from '../../../dist/cjs/src/primitives/BigNumber'
4
6
 
5
7
  describe('PrivateKey', () => {
6
8
  describe('BRC42 vectors', () => {
7
- for (let i = 0; i < BRC42Private.length; i++) {
8
- it(`Passes BRC42 private vector #${i + 1}`, () => {
9
- const v = BRC42Private[i]
10
- const publicKey = PublicKey.fromString(v.senderPublicKey)
11
- const privateKey = PrivateKey.fromString(v.recipientPrivateKey, 16)
12
- const derived = privateKey.deriveChild(publicKey, v.invoiceNumber)
13
- expect(derived.toHex(32)).toEqual(v.privateKey)
9
+ const curve = new Curve()
10
+
11
+ BRC42Private.forEach((vector, index) => {
12
+ it(`Passes BRC42 private vector #${index + 1}`, () => {
13
+ const publicKey = PublicKey.fromString(vector.senderPublicKey)
14
+ const privateKey = PrivateKey.fromString(vector.recipientPrivateKey, 16)
15
+ const derived = privateKey.deriveChild(publicKey, vector.invoiceNumber)
16
+ expect(derived.toHex(32)).toEqual(vector.privateKey)
14
17
  })
18
+ })
19
+ })
20
+
21
+ describe('PrivateKey Validation and Conversion', () => {
22
+ const curve = new Curve()
23
+
24
+ const isValidPrivateKey = (key) => {
25
+ try {
26
+ const keyAsNumber = new BigNumber(key, 16)
27
+ return (
28
+ !keyAsNumber.isZero() &&
29
+ keyAsNumber.cmp(curve.n) < 0 &&
30
+ key.length === 64
31
+ )
32
+ } catch (e) {
33
+ return false
34
+ }
15
35
  }
36
+
37
+ it('Validates and converts valid private keys between hex and string', () => {
38
+ const validKeys = [
39
+ '0000000000000000000000000000000000000000000000000000000000000001',
40
+ 'fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140',
41
+ '8a2f85e08360a04c8a36b7c22c5e9e9a0d3bcf2f95c97db2b8bd90fc5f5ff66a',
42
+ '1b5a8f2392e6959a7de2b0a58f8a64cc528c9bfc1788ee0d32e1455063e71545'
43
+ ]
44
+
45
+ validKeys.forEach((key, index) => {
46
+ const privateKeyFromHex = PrivateKey.fromHex(key)
47
+ const privateKeyFromString = PrivateKey.fromString(key, 'hex')
48
+ const privateKeyToHex = privateKeyFromHex.toHex()
49
+ const privateKeyToString = privateKeyFromString.toString('hex')
50
+ expect(isValidPrivateKey(privateKeyToHex)).toBe(true)
51
+ expect(isValidPrivateKey(privateKeyToString)).toBe(true)
52
+
53
+ // Round-trip conversion checks
54
+ expect(privateKeyToHex).toEqual(key)
55
+ expect(privateKeyToString).toEqual(key)
56
+ })
57
+ })
58
+
59
+ // it('Rejects invalid private keys during validation and conversion', () => {
60
+ // const invalidKeys = [
61
+ // '0000000000000000000000000000000000000000000000000000000000000000',
62
+ // 'fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141',
63
+ // 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff',
64
+ // 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe',
65
+ // '1234567890abcdef',
66
+ // 'fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd03641',
67
+ // 'fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364',
68
+ // ]
69
+
70
+ // invalidKeys.forEach((key, index) => {
71
+ // const isValid = isValidPrivateKey(key)
72
+ // expect(isValid).toBe(false)
73
+ // // Ensure invalid keys throw an error during conversion
74
+ // expect(() => PrivateKey.fromHex(key)).toThrow()
75
+ // expect(() => PrivateKey.fromString(key, 'hex')).toThrow()
76
+ // })
77
+ // })
78
+
79
+ it('Tests 10,000 random private keys for valid conversions', () => {
80
+ for (let i = 0; i < 10000; i++) {
81
+ const privateKey = PrivateKey.fromRandom()
82
+ const privateKeyHex = privateKey.toHex()
83
+ const privateKeyString = privateKey.toString('hex')
84
+
85
+ // Validate the random key's format
86
+ expect(isValidPrivateKey(privateKeyHex)).toBe(true)
87
+ expect(isValidPrivateKey(privateKeyString)).toBe(true)
88
+
89
+ // Round-trip conversion checks
90
+ const roundTripHex = PrivateKey.fromHex(privateKeyHex).toHex()
91
+ const roundTripString = PrivateKey.fromString(privateKeyString, 'hex').toString('hex')
92
+ expect(roundTripHex).toEqual(privateKeyHex)
93
+ expect(roundTripString).toEqual(privateKeyString)
94
+ }
95
+ })
16
96
  })
17
97
  })
@@ -98,6 +98,26 @@ export class Beef {
98
98
  return this.txs.find(tx => tx.txid === txid)
99
99
  }
100
100
 
101
+ /**
102
+ * Replaces `BeefTx` for this txid with txidOnly.
103
+ *
104
+ * Replacement is done so that a `clone()` can be
105
+ * updated by this method without affecting the
106
+ * original.
107
+ *
108
+ * @param txid
109
+ * @returns undefined if txid is unknown.
110
+ */
111
+ makeTxidOnly (txid: string): BeefTx | undefined {
112
+ const i = this.txs.findIndex(tx => tx.txid === txid)
113
+ if (i === -1) return undefined
114
+ let btx = this.txs[i]
115
+ if (btx.isTxidOnly) { return btx }
116
+ this.txs.slice(i, i + 1)
117
+ btx = this.mergeTxidOnly(txid)
118
+ return btx
119
+ }
120
+
101
121
  /**
102
122
  * @returns `MerklePath` with level zero hash equal to txid or undefined.
103
123
  */
@@ -518,7 +538,7 @@ export class Beef {
518
538
 
519
539
  /**
520
540
  * Sort the `txs` by input txid dependency order:
521
- * - Oldest Tx Anchored by Path
541
+ * - Oldest Tx Anchored by Path or txid only
522
542
  * - Newer Txs depending on Older parents
523
543
  * - Newest Tx
524
544
  *
@@ -553,7 +573,10 @@ export class Beef {
553
573
  if (tx.isValid) {
554
574
  validTxids[tx.txid] = true
555
575
  result.push(tx)
556
- } else if (tx.isTxidOnly) { txidOnly.push(tx) } else { queue.push(tx) }
576
+ } else if (tx.isTxidOnly && tx.inputTxids.length === 0) {
577
+ validTxids[tx.txid] = true
578
+ txidOnly.push(tx)
579
+ } else { queue.push(tx) }
557
580
  }
558
581
 
559
582
  // Hashtable of unknown input txids used to fund transactions without their own proof.
@@ -564,17 +587,18 @@ export class Beef {
564
587
  const possiblyMissingInputs = queue
565
588
  queue = []
566
589
 
590
+ // all tx are isValid false, hasProof false.
591
+ // if isTxidOnly then has inputTxids
567
592
  for (const tx of possiblyMissingInputs) {
568
593
  let hasMissingInput = false
569
- if (!tx.isValid) {
570
- // For all the unproven transactions,
571
- // link their inputs that exist in this beef,
572
- // make a note of missing inputs.
573
- for (const inputTxid of tx.inputTxids) {
574
- if (!txidToTx[inputTxid]) {
575
- missingInputs[inputTxid] = true
576
- hasMissingInput = true
577
- }
594
+
595
+ // For all the unproven transactions,
596
+ // link their inputs that exist in this beef,
597
+ // make a note of missing inputs.
598
+ for (const inputTxid of tx.inputTxids) {
599
+ if (!txidToTx[inputTxid]) {
600
+ missingInputs[inputTxid] = true
601
+ hasMissingInput = true
578
602
  }
579
603
  }
580
604
  if (hasMissingInput) { txsMissingInputs.push(tx) } else { queue.push(tx) }
@@ -584,6 +608,8 @@ export class Beef {
584
608
  while (queue.length > 0) {
585
609
  const oldQueue = queue
586
610
  queue = []
611
+ // all tx are isValid false, hasProof false.
612
+ // if isTxidOnly then has inputTxids
587
613
  for (const tx of oldQueue) {
588
614
  if (tx.inputTxids.every(txid => validTxids[txid])) {
589
615
  validTxids[tx.txid] = true
@@ -596,8 +622,8 @@ export class Beef {
596
622
  // transactions that don't have proofs and don't chain to proofs
597
623
  const txsNotValid = queue
598
624
 
599
- // New order of txs is sorted, unsortable, txidOnly (no raw transaction)
600
- this.txs = result.concat(queue).concat(txidOnly).concat(txsMissingInputs)
625
+ // New order of txs is unsortable (missing inputs or depends on missing inputs), txidOnly, sorted (so newest sorted is last)
626
+ this.txs = txsMissingInputs.concat(txsNotValid).concat(txidOnly).concat(result)
601
627
 
602
628
  return {
603
629
  missingInputs: Object.keys(missingInputs),
@@ -305,6 +305,24 @@ describe('Beef tests', () => {
305
305
  expect(atomic).toEqual(beef2)
306
306
  }
307
307
  })
308
+ test('9_sortTxs', async () => {
309
+ {
310
+ const beef = new Beef()
311
+ beef.mergeTxidOnly('a')
312
+ const btx = beef.mergeTxidOnly('b')
313
+ btx.inputTxids = ['a']
314
+ beef.sortTxs()
315
+ expect(beef.txs[1].txid).toBe('b')
316
+ }
317
+ {
318
+ const beef = new Beef()
319
+ const atx = beef.mergeTxidOnly('a')
320
+ const btx = beef.mergeTxidOnly('b')
321
+ atx.inputTxids = ['b']
322
+ beef.sortTxs()
323
+ expect(beef.txs[1].txid).toBe('a')
324
+ }
325
+ })
308
326
  })
309
327
 
310
328
  const txs: string[] = [