-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathelements-cfd-rpc.js
1509 lines (1422 loc) · 51.2 KB
/
elements-cfd-rpc.js
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
// UTF-8
'use strict';
const fs = require('fs')
const ini = require('ini')
const readline = require('readline-sync');
const jsonrpcClientLib = require('./jsonrpc-cli-lib')
const cfdjs = require('cfd-js')
const erpc = require('./elements-rpc.js')
// const bigInt = require('big-integer');
// process.on('unhandledRejection', console.dir);
// load configure
const connInfoFunction = function(path){
let config = {}
try {
fs.statSync(path)
config = ini.parse(fs.readFileSync(path, 'utf-8'))
} catch(err) {
// unknown file
console.log(err)
}
let result = {
bitcoin: {
host: ('mainchainrpchost' in config) ? config.mainchainrpchost : '127.0.0.1',
port: ('mainchainrpcport' in config) ? config.mainchainrpcport : 18443,
user: ('mainchainrpcuser' in config) ? config.mainchainrpcuser : 'bitcoinrpc',
pass: ('mainchainrpcpassword' in config) ? config.mainchainrpcpassword : 'bitcoinrpc'
},
elements: {
host: ('rpcbind' in config) ? config.rpcbind : '127.0.0.1',
port: ('rpcport' in config) ? config.rpcport : 8443,
user: ('rpcuser' in config) ? config.rpcuser : 'bitcoinrpc',
pass: ('rpcpassword' in config) ? config.rpcpassword : 'bitcoinrpc'
}
}
return result
}
const connInfo = connInfoFunction('./command.conf')
const elemConnInfo = jsonrpcClientLib.CreateConnection(connInfo.elements.host, connInfo.elements.port, connInfo.elements.user, connInfo.elements.pass)
const btcConnInfo = jsonrpcClientLib.CreateConnection(connInfo.bitcoin.host, connInfo.bitcoin.port, connInfo.bitcoin.user, connInfo.bitcoin.pass)
let elementsCli = new jsonrpcClientLib.ElementsCli(elemConnInfo)
let btcCli = new jsonrpcClientLib.BitcoinCli(btcConnInfo)
const listunspentMax = 9999999
const toSatoshiAmount = function(amount){
return Number(Math.floor(amount * 100000000));
};
// -----------------------------------------------------------------------------
const SendToNewAddress = async function(amount, blind = true){
let address = await elementsCli.directExecute('getnewaddress', []);
const addressinfo = await elementsCli.directExecute('getaddressinfo', [address])
if ((blind === false) && ('unconfidential' in addressinfo)) {
address = addressinfo.unconfidential
}
const txid = await elementsCli.directExecute('sendtoaddress', [address, amount]);
await elementsCli.directExecute('generatetoaddress', [6, address]);
// const satoshi = Math.ceil(amount * 100000000);
const gettransaction = await elementsCli.directExecute('gettransaction', [txid]);
const tx = await elementsCli.directExecute('decoderawtransaction', [gettransaction.hex]);
let vout = 0;
if (tx.vout[0].value === amount) {
vout = 0;
} else if (tx.vout[1].value === amount) {
vout = 1;
} else if (tx.vout[2].value === amount) {
vout = 2;
} else if ((tx.vout.length > 3) && tx.vout[3].value === amount) {
vout = 3;
} else {
console.log("decode fail. tx=", JSON.stringify(tx, null, 2));
}
return {txid:txid, vout:vout, address:address,};
}
const btcSendToAddress = async function(amount, btcAdrType){
let address = await btcCli.directExecute('getnewaddress', ['', btcAdrType]);
const txid = await btcCli.directExecute('sendtoaddress', [address, amount]);
await btcCli.directExecute('generatetoaddress', [6, address]);
const gettransaction = await btcCli.directExecute('gettransaction', [txid]);
const tx = cfdjs.DecodeRawTransaction({hex: gettransaction.hex, network: 'regtest'});
// console.log('btcSendToAddress: ', JSON.stringify(tx, null, 2));
let vout = 0;
const satoshi = toSatoshiAmount(amount);
if (Number(tx.vout[0].value) === satoshi) {
vout = 0;
} else if ((tx.vout.length > 1) && Number(tx.vout[1].value) === satoshi) {
vout = 1;
} else if ((tx.vout.length > 2) && Number(tx.vout[2].value) === satoshi) {
vout = 2;
} else if ((tx.vout.length > 3) && Number(tx.vout[3].value) === satoshi) {
vout = 3;
} else {
console.log("decode fail. tx=", JSON.stringify(tx, null, 2));
}
return {txid:txid, vout:vout, address:address, amount: amount};
}
const btcCfdSendToAddress = async function(utxo, amount, address){
// createTx
let newAddress = await btcCli.directExecute('getnewaddress', ['', 'bech32']);
const txdata = cfdjs.CreateRawTransaction({
'version': 2,
'locktime': 0,
'txins': [{
'txid': utxo.txid,
'vout': utxo.vout,
'sequence': 4294967295,
}],
'txouts': [{
'address': address,
'amount': toSatoshiAmount(amount),
},{
'address': newAddress,
'amount': toSatoshiAmount(utxo.amount - amount - 0.00002000),
}],
});
// sign
const signTx = await btcCli.directExecute('signrawtransactionwithwallet', [txdata.hex]);
const txid = await btcCli.directExecute('sendrawtransaction', [signTx.hex]);
// await elementsCli.directExecute('generatetoaddress', [6, utxoAddr]);
console.log("txid = " + txid);
// const decTx = cfdjs.DecodeRawTransaction({hex: signTx.hex, network: 'regtest'});
// console.log('btcCfdSendToAddress: ', JSON.stringify(decTx, null, 2));
return {txid: txid, vout: 0};
}
const GenerateKeyPair = function(network = 'regtest', wif = true, isCompressed = true){
const result = cfdjs.CreateKeyPair({
wif: wif,
network: network,
isCompressed: isCompressed,
});
return {pubkey:result.pubkey, privkey:result.privkey,};
}
const CreatePubkeyAddress = function(pubkey, network = 'regtest', hashType = 'p2wpkh'){
const result = cfdjs.CreateAddress({
'keyData': {
'hex': pubkey,
'type': 'pubkey',
},
'network': network,
'isElements': true,
'hashType': hashType,
});
return result.address;
}
const CreateConfidentialPubkeyAddress = function(pubkey, confidentialKey, network = 'regtest', hashType = 'p2wpkh'){
const addr = CreatePubkeyAddress(pubkey, network, hashType);
const result = cfdjs.GetConfidentialAddress({
'unblindedAddress': addr,
'key': confidentialKey,
});
return result.confidentialAddress;
}
const checkString = function(arg, matchText, alias = undefined){
if (arg == matchText) {
return true
} else if ((alias) && (arg == alias)) {
return true
}
return false
}
// -----------------------------------------------------------------------------
const helpDump = function(nameobj) {
if (!nameobj.parameter) {
console.log(' ' + nameobj.name)
} else {
console.log(' ' + nameobj.name + ' ' + nameobj.parameter)
}
if (nameobj.alias) {
console.log(' - alias: ' + nameobj.alias)
}
}
const commandData = {
cfdGenerateKey: {
name: 'cfdGenerateKey',
alias: 'cgenkey',
parameter: '[<network> [<wif> [<isCompressed>]]]'
},
decodeTx: {
name: 'decodeTx',
alias: 'dec',
parameter: '<tx> [<network>]'
},
blindtest_783: {
name: 'blindtest_783',
alias: undefined,
parameter: '[<generateKey(default:false)>]'
},
}
const help = function() {
console.log('usage:')
for (const key in commandData) {
helpDump(commandData[key]);
}
erpc.help();
}
// -----------------------------------------------------------------------------
function strToBool(str) {
return (str == 'true') ? true : false;
}
const toBigInt = function (n) {
let s = bigInt(n).toString(16);
while (s.length < 16) s = '0' + s;
return new Uint8Array(Buffer.from(s, 'hex'));
}
const main = async () =>{
try {
if (process.argv.length <= 2) {
for (var i = 0;i < process.argv.length; i++) {
console.log("argv[" + i + "] = " + process.argv[i]);
}
help()
}
else if (checkString(process.argv[2], "cfdGenerateKey", "cgenkey")) {
let network = 'regtest';
let wif = true;
let isCompressed = true;
if (process.argv.length > 3) network = process.argv[3];
if (process.argv.length > 4) wif = strToBool(process.argv[4]);
if (process.argv.length > 5) isCompressed = strToBool(process.argv[5]);
const result = GenerateKeyPair(network, wif, isCompressed);
console.log(result);
}
else if (checkString(process.argv[2], "decodeTx", "dec")) {
let tx = ''
if (process.argv.length < 4) {
let workTx = readline.question('target tx > ');
tx += workTx.trim();
while (workTx.length > 1020) {
workTx = readline.question('tx input continue > ');
if (workTx.length > 2) {
tx += workTx.trim();
}
}
} else {
tx = process.argv[3]
}
let network = 'regtest';
if (process.argv.length < 5) {
network = readline.question('network > ');
} else {
network = process.argv[4];
}
let decTx = '';
try {
decTx = cfdjs.ElementsDecodeRawTransaction({
hex: tx,
mainchainNetwork: network,
});
console.log(JSON.stringify(decTx, null, 2));
return;
} catch (err) {
}
try {
decTx = cfdjs.DecodeRawTransaction({
hex: tx,
network: network,
});
console.log(JSON.stringify(decTx, null, 2));
} catch (err) {
console.log(err);
console.log(`tx = ${tx}`);
}
}
else if (checkString(process.argv[2], "cfdBtcGetNewAddress", "cbnewaddr")) {
// bitcoin:'mainnet, testnet, regtest'. elements:'liquidv1, regtest'
let network = 'regtest';
// p2wpkh, p2wsh, p2pkh, p2sh, p2sh-p2wpkh, p2sh-p2wsh
let address_type = 'p2wpkh';
let script = false;
let hexData = '';
if (process.argv.length > 3) hexData = process.argv[3];
if (process.argv.length > 4) network = process.argv[4];
if (process.argv.length > 5) address_type = process.argv[5];
if (process.argv.length > 6) script = strToBool(process.argv[6]);
const keyType = (script) ? 'redeem_script' : 'pubkey';
if (hexData === '' && script === false) {
const keyData = GenerateKeyPair(network, true, true);
console.log(keyData);
hexData = keyData.pubkey;
}
const result = cfdjs.CreateAddress({
keyData: {
hex: hexData,
type: keyType,
},
network: network,
hashType: address_type,
});
console.log(result);
}
else if (checkString(process.argv[2], "cfdElmGetNewAddress", "cenewaddr")) {
// bitcoin:'mainnet, testnet, regtest'. elements:'liquidv1, regtest'
let network = 'regtest';
// p2wpkh, p2wsh, p2pkh, p2sh, p2sh-p2wpkh, p2sh-p2wsh
let address_type = 'p2wpkh';
let script = false;
const hexData = process.argv[3];
if (process.argv.length > 4) network = process.argv[4];
if (process.argv.length > 5) address_type = process.argv[5];
if (process.argv.length > 6) script = strToBool(process.argv[6]);
const keyType = (script) ? 'redeem_script' : 'pubkey';
const result = cfdjs.CreateKeyPair({
isElements: true,
keyData: {
hex: hexData,
type: keyType,
},
network: network,
hashType: address_type,
});
console.log(result);
}
// generatefunds
else if (checkString(process.argv[2], "cfdBtcGenerateFunds", "cbgenfund")) {
//
if (process.argv.length < 5) {
console.log("format: cfdBtcGenerateFunds <requireAmount> <address>")
return 0
}
// bitcoin:'mainnet, testnet, regtest'. elements:'liquidv1, regtest'
let network = 'regtest';
const amount = parseInt(process.argv[3]);
const address = process.argv[4];
let sync = false;
if (process.argv.length > 5) sync = strToBool(process.argv[5]);
let totalAmount = 0;
while(totalAmount < amount){
const result = await btcCli.directExecute('generatetoaddress', [1, address, 1000000]);
// console.log(` generatetoaddress = ${result}`)
for(var k = 0; k < result.length; k++){
const blockHash = result[k];
const block = await btcCli.directExecute('getblock', [blockHash]);
for(var i = 0;i < block.tx.length; i++){
const txid = block.tx[i];
const txData = await btcCli.directExecute('getrawtransaction', [txid, false, blockHash]);
// decode tx
const decTx = cfdjs.DecodeRawTransaction({
hex: txData, network: network,
});
for(var j = 0; j < decTx.vout.length; j++){
// console.log(" tx = ", decTx.vout[j])
if (decTx.vout[j].scriptPubKey.addresses) {
if (decTx.vout[j].scriptPubKey.addresses.length === 0) {
// do nothing
} else if (decTx.vout[j].scriptPubKey.addresses[0] === address) {
const amount = decTx.vout[j].value;
console.log(` utxo[${txid},${j}] amount = ${amount}`)
totalAmount = totalAmount + decTx.vout[j].value;
}
}
}
}
}
}
if (sync) {
await btcCli.directExecute('generatetoaddress', [100, address, 1000000]);
}
console.log(` totalAmount = ${totalAmount}`)
}
// sendtoaddress
else if (checkString(process.argv[2], "cfdBtcSendtoaddress", "cbsndaddr")) {
//
}
// wallet command is need internal impl.
// signrawtransactionwithwallet
// getnewaddress
// getaddressinfo
// addmultisigaddress
// dumpprivkey
// estimatesmartfee
// getbalance
// listunspent
// setpaytxfee
// setrelayfee
// validateaddress
// fundrawtransaction
// importaddress
// decoderawtransaction
// GenerateKey : done
// createnewaddress : done
else if (checkString(process.argv[2], "blindtest_783")) {
const assetlabels = await elementsCli.directExecute('dumpassetlabels', [])
const lbtcAsset = assetlabels.bitcoin;
const network = 'regtest';
const hashType = 'p2wpkh';
let genKey = false;
if (process.argv.length > 3) genKey = strToBool(process.argv[3]);
// キー生成
let keys1;
let keys2;
let confKeys1;
let confKeys2;
if (genKey) {
keys1 = GenerateKeyPair(network);
keys2 = GenerateKeyPair(network);
confKeys1 = GenerateKeyPair(network, false);
confKeys2 = GenerateKeyPair(network, false);
} else {
keys1 = {
pubkey: '038fbe823e80ff4fd2368fd1cf04b97626bd1fb2db033ed5a0442ab5e616c14040',
privkey: 'cW7TNDhv5wzXJqCEf1DfFi5ihCkSf5bCCuoFbZbYmGu8WwRjTa4q'
};
keys2 = {
pubkey: '037cdfa375512efb497274e74db9861fca4dbd7a4729e6127f4e063b0c74c79091',
privkey: 'cNpJqHZmmdudazLy7tAK8gky27fRFypC4rQNSapVNX8wVRNUi4go'
};
confKeys1 = {
pubkey: '03a81625d4bd49dd519f65cc81652ca26ecf25fd05e95f9d84d36f84477cfe8927',
privkey: '4a41d64ad4b10ce6bea5859e18d448c3d39ce235708d2348f8e560aed8a6c715'
};
confKeys2 = {
pubkey: '0376995be8c4578187dc903d05888ba52918026c1b3d1ba9f9072e6f01ba76e04e',
privkey: '2a8d0804abeaa461f6223175d797e337455e4be8f015b5de46b0a07d8a138cf3'
};
}
console.log("keys1 =", keys1);
console.log("keys2 =", keys2);
console.log("confKeys1=", confKeys1);
console.log("confKeys2=", confKeys2);
const tx1out1Pubkey = keys1.pubkey;
const tx1out1Privkey = keys1.privkey;
const tx1out2Pubkey = keys2.pubkey;
const tx1out2Privkey = keys2.privkey;
// sendtoaddress (0.01btc, unblind)
const send1 = await SendToNewAddress(0.01, false);
const utxoAddr = send1.address;
const utxoTxid = send1.txid;
const utxoVout = send1.vout;
// cfd createAddress
const tx1out1Addr = CreateConfidentialPubkeyAddress(
tx1out1Pubkey, confKeys1.pubkey, network, hashType);
const tx1out2Addr = CreateConfidentialPubkeyAddress(
tx1out2Pubkey, confKeys2.pubkey, network, hashType);
// createTx
const txdata = cfdjs.ElementsCreateRawTransaction({
'version': 2,
'locktime': 0,
'txins': [{
'txid': utxoTxid,
'vout': utxoVout,
'sequence': 4294967295,
}],
'txouts': [{
'address': tx1out1Addr,
'amount': 900000,
'asset': lbtcAsset,
},{
'address': tx1out2Addr,
'amount': 50000,
'asset': lbtcAsset,
}],
'fee': {
'amount': 50000,
'asset': lbtcAsset,
},
});
// blindTx
const blindTx = cfdjs.BlindRawTransaction({
'tx': txdata.hex,
'txins': [{
'txid': utxoTxid,
'vout': utxoVout,
'asset': lbtcAsset,
'blindFactor': '0000000000000000000000000000000000000000000000000000000000000000',
'assetBlindFactor': '0000000000000000000000000000000000000000000000000000000000000000',
'amount': 1000000,
}],
'txouts': [{
'index': 0,
'blindPubkey': confKeys1.pubkey,
},{
'index': 1,
'blindPubkey': confKeys2.pubkey,
},
],
});
// console.log("blindTx=", JSON.stringify(blindTx, null, 2));
const decodeTx = cfdjs.ElementsDecodeRawTransaction({hex: blindTx.hex, network: network,});
console.log("blindTx=", JSON.stringify(decodeTx, null, 2));
// unblind(for BlindFactor)
const unblindTx = cfdjs.UnblindRawTransaction({
'tx': blindTx.hex,
'txouts': [{
'index': 0,
'blindingKey': confKeys1.privkey,
},{
'index': 1,
'blindingKey': confKeys2.privkey,
},
],
});
console.log("unblindTx=", JSON.stringify(unblindTx, null, 2));
const generator1 = decodeTx.vout[0].assetcommitment
const generator2 = decodeTx.vout[1].assetcommitment
// const generator3 = decodeTx.vout[2].assetcommitment
console.log("generator1 = " + generator1);
console.log("generator2 = " + generator2);
// console.log("generator3 = " + generator3);
// sign, send
const signTx = await elementsCli.directExecute('signrawtransactionwithwallet', [blindTx.hex]);
const txid = await elementsCli.directExecute('sendrawtransaction', [signTx.hex]);
// await elementsCli.directExecute('generatetoaddress', [6, utxoAddr]);
console.log("txid = " + txid);
const send2 = await SendToNewAddress(0.001, false);
// create addr(Confidential)
let address1 = await elementsCli.directExecute('getnewaddress', []);
let address2 = await elementsCli.directExecute('getnewaddress', []);
console.log('address1 = ' + address1);
console.log('address2 = ' + address2);
// createTx
const testTx = cfdjs.ElementsCreateRawTransaction({
'version': 2,
'locktime': 0,
'txins': [{
'txid': txid,
'vout': 0,
'sequence': 4294967295,
},{
'txid': send2.txid,
'vout': send2.vout,
'sequence': 4294967295,
},{
'txid': txid,
'vout': 1,
'sequence': 4294967295,
}],
'txouts': [{
'address': address1,
'amount': 900000,
'asset': lbtcAsset,
},{
'address': address2,
'amount': 100000,
'asset': lbtcAsset,
}],
'fee': {
'amount': 50000,
'asset': lbtcAsset,
},
});
console.log('testTx = ', testTx.hex);
const emptyGen = '000000000000000000000000000000000000000000000000000000000000000000';
let assetgenlist = [generator1, emptyGen, generator2];
const blindTx2 = await elementsCli.directExecute(
'blindrawtransaction', [testTx.hex, true, assetgenlist]);
console.log('blindTx2 = ', blindTx2);
const sighashRet1 = cfdjs.CreateElementsSignatureHash({
tx: blindTx2,
txin: {
'txid': txid,
'vout': 0,
'keyData': {
'hex': tx1out1Pubkey,
'type': 'pubkey',
},
'confidentialValueCommitment': decodeTx.vout[0].valuecommitment,
'hashType': hashType,
},
});
const sighashRet2 = cfdjs.CreateElementsSignatureHash({
tx: blindTx2,
txin: {
'txid': txid,
'vout': 1,
'keyData': {
'hex': tx1out2Pubkey,
'type': 'pubkey',
},
'confidentialValueCommitment': decodeTx.vout[1].valuecommitment,
'hashType': hashType,
},
});
const ecSig1 = cfdjs.CalculateEcSignature({
'sighash': sighashRet1.sighash,
'privkeyData': {
'privkey': tx1out1Privkey,
'network': network,
},
});
const ecSig2 = cfdjs.CalculateEcSignature({
'sighash': sighashRet2.sighash,
'privkeyData': {
'privkey': tx1out2Privkey,
'network': network,
},
});
const sign1 = cfdjs.AddSign({
tx: blindTx2,
isElements: true,
txin: {
txid: txid,
vout: 0,
signParam: [{
hex: ecSig1.signature,
type: 'sign',
derEncode: true,
},{
hex: tx1out1Pubkey,
type: 'pubkey',
},
],
},
});
const sign2 = cfdjs.AddSign({
tx: sign1.hex,
isElements: true,
txin: {
txid: txid,
vout: 1,
signParam: [{
hex: ecSig2.signature,
type: 'sign',
derEncode: true,
},{
hex: tx1out2Pubkey,
type: 'pubkey',
},
],
},
});
const signTx2 = await elementsCli.directExecute('signrawtransactionwithwallet', [sign2.hex]);
const txid2 = await elementsCli.directExecute('sendrawtransaction', [signTx2.hex]);
// await elementsCli.directExecute('generatetoaddress', [6, utxoAddr]);
console.log("txid2 = " + txid2);
}
else if (checkString(process.argv[2], "blindpegin")) {
const network = 'regtest';
const mainchainNetwork = 'regtest';
const amount = Number(process.argv[3]);
let isBlind = true;
let isScript = false;
let fee = 0.001;
if (process.argv.length >= 5) {
fee = Number(process.argv[4]);
}
if (process.argv.length >= 6) {
isBlind = (process.argv[5] === 'true');
}
let targetType = 'bech32'; // 'bech32'; 'p2sh-segwit'
if (process.argv.length >= 7) {
targetType = process.argv[6];
}
if (process.argv.length >= 8) {
isScript = (process.argv[7] === 'true');
}
if (!amount || !fee) {
throw Error('Invalid parameter');
}
const elmAmount = 0.00200000;
const blockNum = 101;
const befGetbalance = await elementsCli.directExecute('getbalance', []);
console.log(` before bitcoin amount = ${befGetbalance.bitcoin}`);
// === pre process ===
// get assetlabels
const assetlabels = await elementsCli.dumpassetlabels();
if (!assetlabels.bitcoin) {
throw Error('bitcoin label not found.');
}
// console.log(`bitcoin asset id = ${assetlabels.bitcoin}`)
// pick token info
const issuances = {};
issuances.before = await elementsCli.listissuances();
// console.log("=== issuances ===\n", issuances.before)
const generateAddr = await elementsCli.getnewaddress();
const adrType = targetType;
let adrHashType = 'p2pkh';
if (adrType === 'bech32') {
adrHashType = 'p2wpkh';
} else if (adrType === 'p2sh-segwit') {
adrHashType = 'p2sh-p2wpkh';
}
// liquid and elements is constant. dynafed is native segwit.
let peginAddrType = 'p2sh-p2wsh';
let peginHashType = 'p2wpkh';
let elemUtxoAddress = await elementsCli.directExecute(
'getnewaddress', ['', adrType]);
// console.log("elemUtxoAddress =>\n", elemUtxoAddress)
const elemUtxoAddressinfo = await elementsCli.directExecute(
'getaddressinfo', [elemUtxoAddress]);
console.log('elemUtxoAddressinfo =>\n', elemUtxoAddressinfo);
if (!isBlind && ('unconfidential' in elemUtxoAddressinfo)) {
elemUtxoAddress = elemUtxoAddressinfo.unconfidential;
console.log('send unconfidential address: ', elemUtxoAddress);
}
const utxoTxid = await elementsCli.directExecute(
'sendtoaddress', [elemUtxoAddress, elmAmount]);
console.log('utxoTxid =>\n', utxoTxid);
await elementsCli.generatetoaddress(1, generateAddr);
let elemSendAddress = await elementsCli.directExecute(
'getnewaddress', ['', adrType]);
const elemSendAddressinfo = await elementsCli.directExecute(
'getaddressinfo', [elemSendAddress]);
console.log('elemSendAddressinfo =>\n', elemSendAddressinfo);
if (!isBlind && ('unconfidential' in elemSendAddressinfo)) {
elemSendAddress = elemSendAddressinfo.unconfidential;
console.log('send unconfidential address: ', elemSendAddress);
}
// === pick input utxo ===
const utxos = {};
const listunspentResult = await elementsCli.listunspent(
0, listunspentMax);
listunspentResult.sort((a, b) => (a.amount - b.amount));
// pick btc utxo (If isBlinded is true, pick blinded utxo)
utxos.btc = listunspentResult.find((unspent) => {
return (unspent.txid === utxoTxid) && (Number(unspent.amount) === elmAmount);
});
if (!utxos.btc) {
throw Error('listunspent fail. Maybe low fee.');
}
console.log('unspents >>\n', JSON.stringify(utxos, null, 2));
const sidechainInfo = await elementsCli.getsidechaininfo();
let elemPeginAddress = await elementsCli.directExecute(
'getnewaddress', ['', adrType]);
const elemPeginAddressinfo = await elementsCli.directExecute(
'getaddressinfo', [elemPeginAddress]);
if (!isBlind && ('unconfidential' in elemPeginAddressinfo)) {
elemPeginAddress = elemPeginAddressinfo.unconfidential;
console.log('pegin address: ', elemPeginAddress);
}
const btcAddress = await btcCli.directExecute('getnewaddress', []);
let elemAddress = await elementsCli.directExecute(
'getnewaddress', ['', adrType]);
console.log('elements confidential address: ', elemAddress);
const addressinfo = await elementsCli.directExecute(
'getaddressinfo', [elemAddress]);
if (!isBlind && ('unconfidential' in addressinfo)) {
elemAddress = addressinfo.unconfidential;
console.log('elements unconfidential address: ', elemAddress);
}
const pegPrivkey = await elementsCli.directExecute(
'dumpprivkey', [elemAddress]);
console.log("elemAddressinfo =>\n", addressinfo)
let elemAddress2 = await elementsCli.directExecute(
'getnewaddress', ['', adrType]);
const addressinfo2 = await elementsCli.directExecute(
'getaddressinfo', [elemAddress2]);
const pegPrivkey2 = await elementsCli.directExecute(
'dumpprivkey', [elemAddress2]);
let paramPeginAddrJson;
let multisigScript = '';
if (isScript) {
const multisig = cfdjs.CreateMultisig({
'nrequired': 2,
'keys': [
addressinfo.pubkey,
addressinfo2.pubkey,
],
'network': network,
'hashType': 'p2sh-p2wsh',
'isElements': true,
});
multisigScript = multisig.witnessScript;
paramPeginAddrJson = {
'fedpegscript': sidechainInfo.fedpegscript,
'redeemScript': multisigScript,
'network': mainchainNetwork,
'hashType': peginAddrType, // if use dynafed, can use p2wsh.
};
} else {
paramPeginAddrJson = {
'fedpegscript': sidechainInfo.fedpegscript,
'pubkey': addressinfo.pubkey,
'network': mainchainNetwork,
'hashType': peginAddrType, // if use dynafed, can use p2wsh.
};
}
const peginaddressInfo = cfdjs.CreatePegInAddress(paramPeginAddrJson);
// const peginaddress = await elementsCli.directExecute(
// 'getpeginaddress', [])
console.log('getpeginaddress =>\n', peginaddressInfo);
const peginAddress = peginaddressInfo.mainchainAddress;
const claimScript = peginaddressInfo.claimScript;
// btc
const btcSnd0 = await btcSendToAddress(amount * 2, adrType);
// console.log('btcSendToAddress: ', btcSnd0);
const btcSnd = await btcCfdSendToAddress(btcSnd0, amount, peginAddress);
console.log('btcSnd =>\n', btcSnd);
const sendTxid = btcSnd.txid;
const sendTxidVout = btcSnd.vout;
await btcCli.directExecute('generatetoaddress', [blockNum, btcAddress]);
const txData = await btcCli.directExecute('gettransaction', [sendTxid]);
const txoutproof = await btcCli.directExecute(
'gettxoutproof', [[sendTxid], txData.blockhash]);
// console.log("gettransaction =>\n", txData)
// console.log("gettxoutproof =>\n", txoutproof)
let utxoAddrinfo = await elementsCli.directExecute(
'getaddressinfo', [utxos.btc.address]);
const utxoConfAddr = (isBlind) ? utxoAddrinfo.confidential : utxos.btc.address;
utxoAddrinfo = await elementsCli.directExecute(
'getaddressinfo', [utxoConfAddr]);
console.log("utxoAddrinfo =>\n", utxoAddrinfo)
console.log("utxoConfAddr =>\n", utxoConfAddr)
const peginBtcTxObj = cfdjs.DecodeRawTransaction({
'hex': txData.hex,
'network': mainchainNetwork,
});
// Pegin ---------------------------------------------------------------
const paramPeginJson = {
'version': 2,
'locktime': 0,
'txins': [{
'isPegin': true,
'txid': sendTxid,
'vout': sendTxidVout,
'sequence': 4294967295,
'peginwitness': {
'amount': toSatoshiAmount(amount),
'asset': assetlabels.bitcoin,
'mainchainGenesisBlockHash': sidechainInfo.parent_blockhash,
'claimScript': claimScript,
'mainchainRawTransaction': txData.hex,
'mainchainTxoutproof': txoutproof,
},
'isRemoveMainchainTxWitness': false,
}, {
'isPegin': false,
'txid': utxos.btc.txid,
'vout': utxos.btc.vout,
'sequence': 4294967295,
}],
'txouts': [{
'address': elemAddress,
'amount': toSatoshiAmount(amount),
'asset': assetlabels.bitcoin,
}, {
'address': elemSendAddress,
'amount': toSatoshiAmount(utxos.btc.amount - fee),
'asset': assetlabels.bitcoin,
}],
'fee': {
'amount': toSatoshiAmount(fee),
'asset': assetlabels.bitcoin,
},
};
// console.log("paramPeginJson =>\n",
// JSON.stringify(paramPeginJson, null, 2))
const peginTx = cfdjs.CreateRawPegin(paramPeginJson);
// const pegin_tx = await elementsCli.directExecute(
// 'createrawpegin', [txData.hex, txoutproof, claimScript])
// console.log("createrawpegin =>\n", pegin_tx)
const peginTxObj = cfdjs.ElementsDecodeRawTransaction({
'hex': peginTx.hex,
'network': network,
});
console.log("peginTxObj =>\n", JSON.stringify(peginTxObj, null, 2))
// === blind transaction ===
let blindTx = peginTx;
if (isBlind) {
blindTx = cfdjs.BlindRawTransaction({
'tx': peginTx.hex,
'txins': [
{
'txid': sendTxid,
'vout': sendTxidVout,
'asset': assetlabels.bitcoin,
'amount': toSatoshiAmount(amount),
'blindFactor': '0000000000000000000000000000000000000000000000000000000000000000', // eslint-disable-line max-len
'assetBlindFactor': '0000000000000000000000000000000000000000000000000000000000000000', // eslint-disable-line max-len
},
{
'txid': utxos.btc.txid,
'vout': utxos.btc.vout,
'asset': utxos.btc.asset,
'blindFactor': utxos.btc.amountblinder,
'assetBlindFactor': utxos.btc.assetblinder,
'amount': toSatoshiAmount(utxos.btc.amount),
},
],
'txouts': [
{
'index': 0,
'blindPubkey': addressinfo.confidential_key,
},
{
'index': 1,
'blindPubkey': utxoAddrinfo.confidential_key,
},
],
});
}
// console.log("blindTx = ", blindTx)
// === sign transaction ===
const inputAddrInfo = {};
let signedTx = blindTx;
// calc signature hash
inputAddrInfo.btc = await elementsCli.getaddressinfo(utxoConfAddr);
let sighashParamJson = {
'tx': signedTx.hex,
'txin': {
'txid': utxos.btc.txid,
'vout': utxos.btc.vout,
'keyData': {
'hex': utxoAddrinfo.pubkey,
'type': 'pubkey',
},
'amount': (!isBlind) ? toSatoshiAmount(utxos.btc.amount) : 0,
'confidentialValueCommitment': (!isBlind) ? '' : utxos.btc.amountcommitment,
'hashType': (adrHashType === 'p2sh-p2wpkh') ? 'p2wpkh' : adrHashType,
'sighashType': 'all',
'sighashAnyoneCanPay': false,
},
};
const sighash = cfdjs.CreateElementsSignatureHash(sighashParamJson);
console.log('sighash = ', sighash);
// calc signature
const privkey = await elementsCli.dumpprivkey(utxoConfAddr);
// let signature = cfdtest.CalculateEcSignature(
// sighash.sighash, privkey, "regtest")
let signature = cfdjs.CalculateEcSignature({
'sighash': sighash.sighash,
'privkeyData': {
'privkey': privkey,
'network': mainchainNetwork,
},
}).signature;
// set sign to wit
signedTx = cfdjs.AddSign({
'tx': signedTx.hex,
'isElements': true,
'txin': {
'txid': utxos.btc.txid,
'vout': utxos.btc.vout,
'isWitness': (adrHashType === 'p2pkh') ? false : true,
'signParam': [
{
'hex': signature,
'type': 'sign',
'derEncode': true,
'sighashType': 'all',
'sighashAnyoneCanPay': false,
},
{
'hex': utxoAddrinfo.pubkey,
'type': 'pubkey',
},
],
},
});
if ((adrHashType !== 'p2pkh') && utxoAddrinfo.isscript) {
let redeemScript = utxoAddrinfo.hex;
if (!redeemScript) {