-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
1167 lines (1041 loc) · 33.6 KB
/
main.go
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
// Copyright (c) 2017 The Decred developers
// Copyright (c) 2018 The Rivine developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package main
import (
"bufio"
"bytes"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"flag"
"fmt"
"net"
"os"
"strconv"
"strings"
"time"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwallet/wallet/txrules"
rpc "github.com/threefoldtech/atomicswap/cmd/btcatomicswap/rpcclient"
"github.com/threefoldtech/atomicswap/timings"
"golang.org/x/crypto/ripemd160"
)
const verify = true
const secretSize = 32
const txVersion = 2
var (
chainParams = &chaincfg.MainNetParams
)
var (
flagset = flag.NewFlagSet("", flag.ExitOnError)
connectFlag = flagset.String("s", "localhost", "host[:port] of Electrum wallet RPC server")
rpcuserFlag = flagset.String("rpcuser", "", "username for wallet RPC authentication")
rpcpassFlag = flagset.String("rpcpass", "", "password for wallet RPC authentication")
testnetFlag = flagset.Bool("testnet", false, "use testnet network")
automatedFlag = flagset.Bool("automated", false, "Use automated/unattended version with json output")
)
// There are two directions that the atomic swap can be performed, as the
// initiator can be on either chain. This tool only deals with creating the
// Bitcoin transactions for these swaps. A second tool should be used for the
// transaction on the other chain. Any chain can be used so long as it supports
// OP_SHA256 and OP_CHECKLOCKTIMEVERIFY.
//
// Example scenerios using bitcoin as the second chain:
//
// Scenerio 1:
// cp1 initiates (dcr)
// cp2 participates with cp1 H(S) (btc)
// cp1 redeems btc revealing S
// - must verify H(S) in contract is hash of known secret
// cp2 redeems dcr with S
//
// Scenerio 2:
// cp1 initiates (btc)
// cp2 participates with cp1 H(S) (dcr)
// cp1 redeems dcr revealing S
// - must verify H(S) in contract is hash of known secret
// cp2 redeems btc with S
func init() {
flagset.Usage = func() {
fmt.Println("Atomic swaps for Bitcoin using the Electrum wallet")
fmt.Println("Usage: btcatomicswap [flags] cmd [cmd args]")
fmt.Println()
fmt.Println("Commands:")
fmt.Println(" initiate <participant address> <amount>")
fmt.Println(" participate <initiator address> <amount> <secret hash>")
fmt.Println(" redeem <contract> <contract transaction> <secret>")
fmt.Println(" refund <contract> <contract transaction>")
fmt.Println(" extractsecret <redemption transaction> <secret hash>")
fmt.Println(" auditcontract <contract> <contract transaction>")
fmt.Println()
fmt.Println("Flags:")
flagset.PrintDefaults()
}
}
type command interface {
runCommand(*rpc.Client) error
}
// offline commands don't require wallet RPC.
type offlineCommand interface {
command
runOfflineCommand() error
}
type initiateCmd struct {
cp2Addr *btcutil.AddressPubKeyHash
amount btcutil.Amount
}
type participateCmd struct {
cp1Addr *btcutil.AddressPubKeyHash
amount btcutil.Amount
secretHash []byte
}
type redeemCmd struct {
contract []byte
contractTx *wire.MsgTx
secret []byte
}
type refundCmd struct {
contract []byte
contractTx *wire.MsgTx
}
type extractSecretCmd struct {
redemptionTx *wire.MsgTx
secretHash []byte
}
type auditContractCmd struct {
contract []byte
contractTx *wire.MsgTx
}
func main() {
showUsage, err := run()
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
if showUsage {
flagset.Usage()
}
if err != nil || showUsage {
os.Exit(1)
}
}
func checkCmdArgLength(args []string, required int) (nArgs int) {
if len(args) < required {
return 0
}
for i, arg := range args[:required] {
if len(arg) != 1 && strings.HasPrefix(arg, "-") {
return i
}
}
return required
}
func run() (showUsage bool, err error) {
flagset.Parse(os.Args[1:])
args := flagset.Args()
if len(args) == 0 {
return true, nil
}
cmdArgs := 0
switch args[0] {
case "initiate":
cmdArgs = 2
case "participate":
cmdArgs = 3
case "redeem":
cmdArgs = 3
case "refund":
cmdArgs = 2
case "extractsecret":
cmdArgs = 2
case "auditcontract":
cmdArgs = 2
default:
return true, fmt.Errorf("unknown command %v", args[0])
}
nArgs := checkCmdArgLength(args[1:], cmdArgs)
flagset.Parse(args[1+nArgs:])
if nArgs < cmdArgs {
return true, fmt.Errorf("%s: too few arguments", args[0])
}
if flagset.NArg() != 0 {
return true, fmt.Errorf("unexpected argument: %s", flagset.Arg(0))
}
if *testnetFlag {
chainParams = &chaincfg.TestNet3Params
}
var cmd command
switch args[0] {
case "initiate":
cp2Addr, err := btcutil.DecodeAddress(args[1], chainParams)
if err != nil {
return true, fmt.Errorf("failed to decode participant address: %v", err)
}
if !cp2Addr.IsForNet(chainParams) {
return true, fmt.Errorf("participant address is not "+
"intended for use on %v", chainParams.Name)
}
cp2AddrP2PKH, ok := cp2Addr.(*btcutil.AddressPubKeyHash)
if !ok {
return true, errors.New("participant address is not P2PKH")
}
amountF64, err := strconv.ParseFloat(args[2], 64)
if err != nil {
return true, fmt.Errorf("failed to decode amount: %v", err)
}
amount, err := btcutil.NewAmount(amountF64)
if err != nil {
return true, err
}
cmd = &initiateCmd{cp2Addr: cp2AddrP2PKH, amount: amount}
case "participate":
cp1Addr, err := btcutil.DecodeAddress(args[1], chainParams)
if err != nil {
return true, fmt.Errorf("failed to decode initiator address: %v", err)
}
if !cp1Addr.IsForNet(chainParams) {
return true, fmt.Errorf("initiator address is not "+
"intended for use on %v", chainParams.Name)
}
cp1AddrP2PKH, ok := cp1Addr.(*btcutil.AddressPubKeyHash)
if !ok {
return true, errors.New("initiator address is not P2PKH")
}
amountF64, err := strconv.ParseFloat(args[2], 64)
if err != nil {
return true, fmt.Errorf("failed to decode amount: %v", err)
}
amount, err := btcutil.NewAmount(amountF64)
if err != nil {
return true, err
}
secretHash, err := hex.DecodeString(args[3])
if err != nil {
return true, errors.New("secret hash must be hex encoded")
}
if len(secretHash) != sha256.Size {
return true, errors.New("secret hash has wrong size")
}
cmd = &participateCmd{cp1Addr: cp1AddrP2PKH, amount: amount, secretHash: secretHash}
case "redeem":
contract, err := hex.DecodeString(args[1])
if err != nil {
return true, fmt.Errorf("failed to decode contract: %v", err)
}
contractTxBytes, err := hex.DecodeString(args[2])
if err != nil {
return true, fmt.Errorf("failed to decode contract transaction: %v", err)
}
var contractTx wire.MsgTx
err = contractTx.Deserialize(bytes.NewReader(contractTxBytes))
if err != nil {
return true, fmt.Errorf("failed to decode contract transaction: %v", err)
}
secret, err := hex.DecodeString(args[3])
if err != nil {
return true, fmt.Errorf("failed to decode secret: %v", err)
}
cmd = &redeemCmd{contract: contract, contractTx: &contractTx, secret: secret}
case "refund":
contract, err := hex.DecodeString(args[1])
if err != nil {
return true, fmt.Errorf("failed to decode contract: %v", err)
}
contractTxBytes, err := hex.DecodeString(args[2])
if err != nil {
return true, fmt.Errorf("failed to decode contract transaction: %v", err)
}
var contractTx wire.MsgTx
err = contractTx.Deserialize(bytes.NewReader(contractTxBytes))
if err != nil {
return true, fmt.Errorf("failed to decode contract transaction: %v", err)
}
cmd = &refundCmd{contract: contract, contractTx: &contractTx}
case "extractsecret":
redemptionTxBytes, err := hex.DecodeString(args[1])
if err != nil {
return true, fmt.Errorf("failed to decode redemption transaction: %v", err)
}
var redemptionTx wire.MsgTx
err = redemptionTx.Deserialize(bytes.NewReader(redemptionTxBytes))
if err != nil {
return true, fmt.Errorf("failed to decode redemption transaction: %v", err)
}
secretHash, err := hex.DecodeString(args[2])
if err != nil {
return true, errors.New("secret hash must be hex encoded")
}
if len(secretHash) != sha256.Size {
return true, errors.New("secret hash has wrong size")
}
cmd = &extractSecretCmd{redemptionTx: &redemptionTx, secretHash: secretHash}
case "auditcontract":
contract, err := hex.DecodeString(args[1])
if err != nil {
return true, fmt.Errorf("failed to decode contract: %v", err)
}
contractTxBytes, err := hex.DecodeString(args[2])
if err != nil {
return true, fmt.Errorf("failed to decode contract transaction: %v", err)
}
var contractTx wire.MsgTx
err = contractTx.Deserialize(bytes.NewReader(contractTxBytes))
if err != nil {
return true, fmt.Errorf("failed to decode contract transaction: %v", err)
}
cmd = &auditContractCmd{contract: contract, contractTx: &contractTx}
}
// Offline commands don't need to talk to the wallet.
if cmd, ok := cmd.(offlineCommand); ok {
return false, cmd.runOfflineCommand()
}
connect, err := normalizeAddress(*connectFlag, walletPort(chainParams))
if err != nil {
return true, fmt.Errorf("wallet server address: %v", err)
}
connConfig := &rpc.ConnConfig{
Host: connect,
User: *rpcuserFlag,
Pass: *rpcpassFlag,
DisableTLS: true,
HTTPPostMode: true,
}
client, err := rpc.New(connConfig)
if err != nil {
return false, fmt.Errorf("rpc connect: %v", err)
}
defer func() {
client.Shutdown()
client.WaitForShutdown()
}()
err = cmd.runCommand(client)
return false, err
}
func normalizeAddress(addr string, defaultPort string) (hostport string, err error) {
host, port, origErr := net.SplitHostPort(addr)
if origErr == nil {
return net.JoinHostPort(host, port), nil
}
addr = net.JoinHostPort(addr, defaultPort)
_, _, err = net.SplitHostPort(addr)
if err != nil {
return "", origErr
}
return addr, nil
}
func walletPort(params *chaincfg.Params) string {
switch params {
case &chaincfg.MainNetParams:
return "8332"
case &chaincfg.TestNet3Params:
return "18332"
default:
return ""
}
}
// createSig creates and returns the serialized raw signature and compressed
// pubkey for a transaction input signature. Due to limitations of the Bitcoin
// Core RPC API, this requires dumping a private key and signing in the client,
// rather than letting the wallet sign.
func createSig(tx *wire.MsgTx, idx int, pkScript []byte, addr btcutil.Address,
c *rpc.Client) (sig, pubkey []byte, err error) {
wif, err := c.DumpPrivKey(addr)
if err != nil {
return nil, nil, err
}
sig, err = txscript.RawTxInSignature(tx, idx, pkScript, txscript.SigHashAll, wif.PrivKey)
if err != nil {
return nil, nil, err
}
return sig, wif.PrivKey.PubKey().SerializeCompressed(), nil
}
// payTo calls a the payto JSON-RPC method,
//It creates a funded ,signed transaction.
func payTo(c *rpc.Client, destination btcutil.Address, amount btcutil.Amount) (fundedTx *wire.MsgTx, fee btcutil.Amount, err error) {
fundedTx, complete, err := c.PayTo(destination, amount, false)
if err != nil {
return
}
if !complete {
err = errors.New("payto:Created transaction is not complete")
}
//Fetch all unspent outputs from the wallet in order to calculate the fee
utxos, err := c.ListUnspent()
if err != nil {
return
}
findUtxofunc := func(outPoint wire.OutPoint) (*rpc.UnspentOutput, error) {
for _, utxo := range utxos {
if outPoint.Hash.IsEqual(&utxo.OutPoint.Hash) && outPoint.Index == utxo.OutPoint.Index {
return utxo, nil
}
}
return nil, fmt.Errorf("no utxo found for used input %s", outPoint)
}
var rawfee int64
for _, txin := range fundedTx.TxIn {
utxo, err := findUtxofunc(txin.PreviousOutPoint)
if err != nil {
return nil, 0, err
}
rawfee += int64(utxo.Value)
}
for _, txout := range fundedTx.TxOut {
rawfee -= txout.Value
}
fee = btcutil.Amount(rawfee)
return
}
// getFeePerKb queries the wallet for the current optimal fee rate per kilobyte,
// according to config settings(static/dynamic).
func getFeePerKb(c *rpc.Client) (feerate btcutil.Amount, err error) {
return c.GetFeeRate()
}
// getUnusedAddress uses the getunusedeaddress JSON-RPC method.
func getUnusedAddress(c *rpc.Client) (btcutil.Address, error) {
addr, err := c.GetUnusedAddress()
if err != nil {
return nil, err
}
if !addr.IsForNet(chainParams) {
return nil, fmt.Errorf("address %v is not intended for use on %v",
addr, chainParams.Name)
}
if _, ok := addr.(*btcutil.AddressPubKeyHash); !ok {
return nil, fmt.Errorf("address %v is not P2PKH",
addr)
}
return addr, nil
}
func promptPublishTx(c *rpc.Client, tx *wire.MsgTx, name string) error {
if !*automatedFlag {
reader := bufio.NewReader(os.Stdin)
L:
for {
fmt.Printf("Publish %s transaction? [y/N] ", name)
answer, err := reader.ReadString('\n')
if err != nil {
return err
}
answer = strings.TrimSpace(strings.ToLower(answer))
switch answer {
case "y", "yes":
break L
case "n", "no", "":
return nil
default:
fmt.Println("please answer y or n")
continue
}
}
}
txHash, err := c.SendRawTransaction(tx, false)
if err != nil {
return fmt.Errorf("sendrawtransaction: %v", err)
}
if !*automatedFlag {
fmt.Printf("Published %s transaction (%v)\n", name, txHash)
}
return nil
}
// contractArgs specifies the common parameters used to create the initiator's
// and participant's contract.
type contractArgs struct {
them *btcutil.AddressPubKeyHash
amount btcutil.Amount
locktime int64
secretHash []byte
}
// builtContract houses the details regarding a contract and the contract
// payment transaction, as well as the transaction to perform a refund.
type builtContract struct {
contract []byte
contractP2SH btcutil.Address
contractTxHash *chainhash.Hash
contractTx *wire.MsgTx
contractFee btcutil.Amount
refundTx *wire.MsgTx
refundFee btcutil.Amount
}
// buildContract creates a contract for the parameters specified in args, using
// wallet RPC to generate an internal address to redeem the refund and to sign
// the payment to the contract transaction.
func buildContract(c *rpc.Client, args *contractArgs) (*builtContract, error) {
refundAddr, err := getUnusedAddress(c)
if err != nil {
return nil, fmt.Errorf("getunusedaddress: %v", err)
}
refundAddrH, ok := refundAddr.(interface {
Hash160() *[ripemd160.Size]byte
})
if !ok {
return nil, errors.New("unable to create hash160 from change address")
}
contract, err := atomicSwapContract(refundAddrH.Hash160(), args.them.Hash160(),
args.locktime, args.secretHash)
if err != nil {
return nil, err
}
contractP2SH, err := btcutil.NewAddressScriptHash(contract, chainParams)
if err != nil {
return nil, err
}
//contractP2SHPkScript, err := txscript.PayToAddrScript(contractP2SH)
//if err != nil {
// return nil, err
//}
feePerKb, err := getFeePerKb(c)
if err != nil {
return nil, err
}
contractTx, contractFee, err := payTo(c, contractP2SH, args.amount)
// unsignedContract := wire.NewMsgTx(txVersion)
// unsignedContract.AddTxOut(wire.NewTxOut(int64(args.amount), contractP2SHPkScript))
// unsignedContract, contractFee, err := fundRawTransaction(c, unsignedContract, feePerKb)
// if err != nil {
// return nil, fmt.Errorf("fundrawtransaction: %v", err)
// }
// contractTx, complete, err := c.SignRawTransaction(unsignedContract)
if err != nil {
return nil, fmt.Errorf("payTo: %v", err)
}
contractTxHash := contractTx.TxHash()
refundTx, refundFee, err := buildRefund(c, contract, contractTx, feePerKb)
if err != nil {
return nil, err
}
return &builtContract{
contract,
contractP2SH,
&contractTxHash,
contractTx,
contractFee,
refundTx,
refundFee,
}, nil
}
func buildRefund(c *rpc.Client, contract []byte, contractTx *wire.MsgTx, feePerKb btcutil.Amount) (
refundTx *wire.MsgTx, refundFee btcutil.Amount, err error) {
contractP2SH, err := btcutil.NewAddressScriptHash(contract, chainParams)
if err != nil {
return nil, 0, err
}
contractP2SHPkScript, err := txscript.PayToAddrScript(contractP2SH)
if err != nil {
return nil, 0, err
}
contractTxHash := contractTx.TxHash()
contractOutPoint := wire.OutPoint{Hash: contractTxHash, Index: ^uint32(0)}
for i, o := range contractTx.TxOut {
if bytes.Equal(o.PkScript, contractP2SHPkScript) {
contractOutPoint.Index = uint32(i)
break
}
}
if contractOutPoint.Index == ^uint32(0) {
return nil, 0, errors.New("contract tx does not contain a P2SH contract payment")
}
refundAddress, err := getUnusedAddress(c)
if err != nil {
return nil, 0, fmt.Errorf("getunusedaddress: %v", err)
}
refundOutScript, err := txscript.PayToAddrScript(refundAddress)
if err != nil {
return nil, 0, err
}
pushes, err := txscript.ExtractAtomicSwapDataPushes(0, contract)
if err != nil {
// expected to only be called with good input
panic(err)
}
refundAddr, err := btcutil.NewAddressPubKeyHash(pushes.RefundHash160[:], chainParams)
if err != nil {
return nil, 0, err
}
refundTx = wire.NewMsgTx(txVersion)
refundTx.LockTime = uint32(pushes.LockTime)
refundTx.AddTxOut(wire.NewTxOut(0, refundOutScript)) // amount set below
refundSize := estimateRefundSerializeSize(contract, refundTx.TxOut)
refundFee = txrules.FeeForSerializeSize(feePerKb, refundSize)
refundTx.TxOut[0].Value = contractTx.TxOut[contractOutPoint.Index].Value - int64(refundFee)
if txrules.IsDustOutput(refundTx.TxOut[0], feePerKb) {
return nil, 0, fmt.Errorf("refund output value of %v is dust", btcutil.Amount(refundTx.TxOut[0].Value))
}
txIn := wire.NewTxIn(&contractOutPoint, nil, nil)
txIn.Sequence = 0
refundTx.AddTxIn(txIn)
refundSig, refundPubKey, err := createSig(refundTx, 0, contract, refundAddr, c)
if err != nil {
return nil, 0, err
}
refundSigScript, err := refundP2SHContract(contract, refundSig, refundPubKey)
if err != nil {
return nil, 0, err
}
refundTx.TxIn[0].SignatureScript = refundSigScript
if verify {
e, err := txscript.NewEngine(contractTx.TxOut[contractOutPoint.Index].PkScript,
refundTx, 0, txscript.StandardVerifyFlags, txscript.NewSigCache(10),
txscript.NewTxSigHashes(refundTx), contractTx.TxOut[contractOutPoint.Index].Value)
if err != nil {
panic(err)
}
err = e.Execute()
if err != nil {
panic(err)
}
}
return refundTx, refundFee, nil
}
func sha256Hash(x []byte) []byte {
h := sha256.Sum256(x)
return h[:]
}
func calcFeePerKb(absoluteFee btcutil.Amount, serializeSize int) float64 {
return float64(absoluteFee) / float64(serializeSize) / 1e5
}
func (cmd *initiateCmd) runCommand(c *rpc.Client) error {
var secret [secretSize]byte
_, err := rand.Read(secret[:])
if err != nil {
return err
}
secretHash := sha256Hash(secret[:])
// locktime after 500,000,000 (Tue Nov 5 00:53:20 1985 UTC) is interpreted
// as a unix time rather than a block height.
locktime := time.Now().Add(timings.LockTime).Unix()
b, err := buildContract(c, &contractArgs{
them: cmd.cp2Addr,
amount: cmd.amount,
locktime: locktime,
secretHash: secretHash,
})
if err != nil {
return err
}
refundTxHash := b.refundTx.TxHash()
contractFeePerKb := calcFeePerKb(b.contractFee, b.contractTx.SerializeSize())
refundFeePerKb := calcFeePerKb(b.refundFee, b.refundTx.SerializeSize())
var contractBuf bytes.Buffer
contractBuf.Grow(b.contractTx.SerializeSize())
b.contractTx.Serialize(&contractBuf)
var refundBuf bytes.Buffer
refundBuf.Grow(b.refundTx.SerializeSize())
b.refundTx.Serialize(&refundBuf)
if !*automatedFlag {
fmt.Printf("Secret: %x\n", secret)
fmt.Printf("Secret hash: %x\n\n", secretHash)
fmt.Printf("Contract fee: %v (%0.8f BTC/kB)\n", b.contractFee, contractFeePerKb)
fmt.Printf("Refund fee: %v (%0.8f BTC/kB)\n\n", b.refundFee, refundFeePerKb)
fmt.Printf("Contract (%v):\n", b.contractP2SH)
fmt.Printf("%x\n\n", b.contract)
fmt.Printf("Contract transaction (%v):\n", b.contractTxHash)
fmt.Printf("%x\n\n", contractBuf.Bytes())
fmt.Printf("Refund transaction (%v):\n", &refundTxHash)
fmt.Printf("%x\n\n", refundBuf.Bytes())
} else {
output := struct {
Secret string `json:"secret"`
SecretHash string `json:"hash"`
ContractFee string `json:"contractfee"`
Refundfee string `json:"refundfee"`
ContractP2Sh string `json:"contractp2sh"`
Contract string `json:"contract"`
ContractTransactionHash string `json:"contractTransactionHash"`
ContractTransaction string `json:"contractTransaction"`
RefundTransactionHash string `json:"refundTransactionHash"`
RefundTransaction string `json:"refundTransaction"`
}{
fmt.Sprintf("%x", secret),
fmt.Sprintf("%x", secretHash),
fmt.Sprintf("%v", b.contractFee),
fmt.Sprintf("%v", b.refundFee),
fmt.Sprintf("%v", b.contractP2SH),
fmt.Sprintf("%x", b.contract),
fmt.Sprintf("%v", b.contractTxHash),
fmt.Sprintf("%x", contractBuf.Bytes()),
fmt.Sprintf("%v", &refundTxHash),
fmt.Sprintf("%x", refundBuf.Bytes()),
}
jsonoutput, _ := json.Marshal(output)
fmt.Println(string(jsonoutput))
}
return promptPublishTx(c, b.contractTx, "contract")
}
func (cmd *participateCmd) runCommand(c *rpc.Client) error {
// locktime after 500,000,000 (Tue Nov 5 00:53:20 1985 UTC) is interpreted
// as a unix time rather than a block height.
locktime := time.Now().Add(timings.LockTime / 2).Unix()
b, err := buildContract(c, &contractArgs{
them: cmd.cp1Addr,
amount: cmd.amount,
locktime: locktime,
secretHash: cmd.secretHash,
})
if err != nil {
return err
}
refundTxHash := b.refundTx.TxHash()
contractFeePerKb := calcFeePerKb(b.contractFee, b.contractTx.SerializeSize())
refundFeePerKb := calcFeePerKb(b.refundFee, b.refundTx.SerializeSize())
var contractBuf bytes.Buffer
contractBuf.Grow(b.contractTx.SerializeSize())
b.contractTx.Serialize(&contractBuf)
var refundBuf bytes.Buffer
refundBuf.Grow(b.refundTx.SerializeSize())
b.refundTx.Serialize(&refundBuf)
if !*automatedFlag {
fmt.Printf("Contract fee: %v (%0.8f BTC/kB)\n", b.contractFee, contractFeePerKb)
fmt.Printf("Refund fee: %v (%0.8f BTC/kB)\n\n", b.refundFee, refundFeePerKb)
fmt.Printf("Contract (%v):\n", b.contractP2SH)
fmt.Printf("%x\n\n", b.contract)
fmt.Printf("Contract transaction (%v):\n", b.contractTxHash)
fmt.Printf("%x\n\n", contractBuf.Bytes())
fmt.Printf("Refund transaction (%v):\n", &refundTxHash)
fmt.Printf("%x\n\n", refundBuf.Bytes())
} else {
output := struct {
ContractFee string `json:"contractfee"`
Refundfee string `json:"refundfee"`
ContractP2Sh string `json:"contract"`
ContractTransaction string `json:"contractTransaction"`
RefundTransactionHash string `json:"refundTransaction"`
}{
fmt.Sprintf("%v", b.contractFee),
fmt.Sprintf("%v", b.refundFee),
fmt.Sprintf("%v", b.contractP2SH),
fmt.Sprintf("%v", b.contractTxHash),
fmt.Sprintf("%v", &refundTxHash),
}
jsonoutput, _ := json.Marshal(output)
fmt.Println(string(jsonoutput))
}
return promptPublishTx(c, b.contractTx, "contract")
}
func (cmd *redeemCmd) runCommand(c *rpc.Client) error {
pushes, err := txscript.ExtractAtomicSwapDataPushes(0, cmd.contract)
if err != nil {
return err
}
if pushes == nil {
return errors.New("contract is not an atomic swap script recognized by this tool")
}
recipientAddr, err := btcutil.NewAddressPubKeyHash(pushes.RecipientHash160[:],
chainParams)
if err != nil {
return err
}
contractHash := btcutil.Hash160(cmd.contract)
contractOut := -1
for i, out := range cmd.contractTx.TxOut {
sc, addrs, _, _ := txscript.ExtractPkScriptAddrs(out.PkScript, chainParams)
if sc == txscript.ScriptHashTy &&
bytes.Equal(addrs[0].(*btcutil.AddressScriptHash).Hash160()[:], contractHash) {
contractOut = i
break
}
}
if contractOut == -1 {
return errors.New("transaction does not contain a contract output")
}
addr, err := getUnusedAddress(c)
if err != nil {
return fmt.Errorf("getrawchangeaddres: %v", err)
}
outScript, err := txscript.PayToAddrScript(addr)
if err != nil {
return err
}
contractTxHash := cmd.contractTx.TxHash()
contractOutPoint := wire.OutPoint{
Hash: contractTxHash,
Index: uint32(contractOut),
}
feePerKb, err := getFeePerKb(c)
if err != nil {
return err
}
redeemTx := wire.NewMsgTx(txVersion)
redeemTx.LockTime = uint32(pushes.LockTime)
redeemTx.AddTxIn(wire.NewTxIn(&contractOutPoint, nil, nil))
redeemTx.AddTxOut(wire.NewTxOut(0, outScript)) // amount set below
redeemSize := estimateRedeemSerializeSize(cmd.contract, redeemTx.TxOut)
fee := txrules.FeeForSerializeSize(feePerKb, redeemSize)
redeemTx.TxOut[0].Value = cmd.contractTx.TxOut[contractOut].Value - int64(fee)
if txrules.IsDustOutput(redeemTx.TxOut[0], feePerKb) {
return fmt.Errorf("redeem output value of %v is dust", btcutil.Amount(redeemTx.TxOut[0].Value))
}
redeemSig, redeemPubKey, err := createSig(redeemTx, 0, cmd.contract, recipientAddr, c)
if err != nil {
return err
}
redeemSigScript, err := redeemP2SHContract(cmd.contract, redeemSig, redeemPubKey, cmd.secret)
if err != nil {
return err
}
redeemTx.TxIn[0].SignatureScript = redeemSigScript
redeemTxHash := redeemTx.TxHash()
redeemFeePerKb := calcFeePerKb(fee, redeemTx.SerializeSize())
var buf bytes.Buffer
buf.Grow(redeemTx.SerializeSize())
redeemTx.Serialize(&buf)
if !*automatedFlag {
fmt.Printf("Redeem fee: %v (%0.8f BTC/kB)\n\n", fee, redeemFeePerKb)
fmt.Printf("Redeem transaction (%v):\n", &redeemTxHash)
fmt.Printf("%x\n\n", buf.Bytes())
} else {
output := struct {
RedeemFee string `json:"redeemFee"`
RedeemTransactionTxHash string `json:"redeemTransaction"`
}{
fmt.Sprintf("%v", fee),
fmt.Sprintf("%v", &redeemTxHash),
}
jsonoutput, _ := json.Marshal(output)
fmt.Println(string(jsonoutput))
}
if verify {
e, err := txscript.NewEngine(cmd.contractTx.TxOut[contractOutPoint.Index].PkScript,
redeemTx, 0, txscript.StandardVerifyFlags, txscript.NewSigCache(10),
txscript.NewTxSigHashes(redeemTx), cmd.contractTx.TxOut[contractOut].Value)
if err != nil {
panic(err)
}
err = e.Execute()
if err != nil {
panic(err)
}
}
return promptPublishTx(c, redeemTx, "redeem")
}
func (cmd *refundCmd) runCommand(c *rpc.Client) error {
pushes, err := txscript.ExtractAtomicSwapDataPushes(0, cmd.contract)
if err != nil {
return err
}
if pushes == nil {
return errors.New("contract is not an atomic swap script recognized by this tool")
}
feePerKb, err := getFeePerKb(c)
if err != nil {
return err
}
refundTx, refundFee, err := buildRefund(c, cmd.contract, cmd.contractTx, feePerKb)
if err != nil {
return err
}
refundTxHash := refundTx.TxHash()
var buf bytes.Buffer
buf.Grow(refundTx.SerializeSize())
refundTx.Serialize(&buf)
refundFeePerKb := calcFeePerKb(refundFee, refundTx.SerializeSize())
if !*automatedFlag {
fmt.Printf("Refund fee: %v (%0.8f BTC/kB)\n\n", refundFee, refundFeePerKb)
fmt.Printf("Refund transaction (%v):\n", &refundTxHash)
fmt.Printf("%x\n\n", buf.Bytes())
} else {
output := struct {
RefundFee string `json:"refundFee"`
RefundTransactionTxHash string `json:"refundTransaction"`
}{
fmt.Sprintf("%v", refundFee),
fmt.Sprintf("%v", &refundTxHash),
}
jsonoutput, _ := json.Marshal(output)
fmt.Println(string(jsonoutput))
}
return promptPublishTx(c, refundTx, "refund")
}
func (cmd *extractSecretCmd) runCommand(c *rpc.Client) error {
return cmd.runOfflineCommand()
}
func (cmd *extractSecretCmd) runOfflineCommand() error {
// Loop over all pushed data from all inputs, searching for one that hashes
// to the expected hash. By searching through all data pushes, we avoid any
// issues that could be caused by the initiator redeeming the participant's
// contract with some "nonstandard" or unrecognized transaction or script
// type.
for _, in := range cmd.redemptionTx.TxIn {
pushes, err := txscript.PushedData(in.SignatureScript)
if err != nil {
return err
}
for _, push := range pushes {
if bytes.Equal(sha256Hash(push), cmd.secretHash) {
fmt.Printf("Secret: %x\n", push)
return nil
}
}
}
return errors.New("transaction does not contain the secret")
}
func (cmd *auditContractCmd) runCommand(c *rpc.Client) error {
return cmd.runOfflineCommand()
}
func (cmd *auditContractCmd) runOfflineCommand() error {
contractHash160 := btcutil.Hash160(cmd.contract)
contractOut := -1
for i, out := range cmd.contractTx.TxOut {
sc, addrs, _, err := txscript.ExtractPkScriptAddrs(out.PkScript, chainParams)
if err != nil || sc != txscript.ScriptHashTy {
continue
}