/
participation.go
92 lines (75 loc) · 2.68 KB
/
participation.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
// Copyright (c) 2018/2019 The DevCo developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package dcr
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"time"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/dcrutil"
"github.com/devwarrior777/atomicswap/libs"
)
// participate builds a contract & a contract transaction depending upon the hash of the
// (shared) secret. The participant will know the secret only when initiator redeems the
// contract made here
func participate(testnet bool, rpcinfo libs.RPCInfo, params libs.ParticipateParams) (*libs.ParticipateResult, error) {
chainParams := getChainParams(testnet)
cp1Addr, err := dcrutil.DecodeAddress(params.CP1Addr)
if err != nil {
return nil, fmt.Errorf("failed to decode initiator address: %v", err)
}
if !cp1Addr.IsForNet(chainParams) {
return nil, fmt.Errorf("initiator address is not intended for use on %v", chainParams.Name)
}
cp1AddrP2PKH, ok := cp1Addr.(*dcrutil.AddressPubKeyHash)
if !ok {
return nil, errors.New("initiator address is not P2PKH")
}
cp1Amount := dcrutil.Amount(params.CP1Amount)
secretHash, err := hex.DecodeString(params.SecretHash)
if err != nil {
return nil, errors.New("secret hash must be hex encoded")
}
if len(secretHash) != sha256.Size {
return nil, errors.New("secret hash has wrong size")
}
// 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(24 * time.Hour).Unix()
// locktime := time.Now().Add(24 * time.Minute).Unix() //Test
wallet, err := startRPC(testnet, rpcinfo)
if err != nil {
return nil, err
}
defer wallet.stopRPC()
b, err := buildContract(testnet, wallet.client, &contractArgs{
them: cp1AddrP2PKH,
amount: cp1Amount,
locktime: locktime,
secretHash: secretHash,
}, rpcinfo.WalletPass)
if err != nil {
return nil, err
}
contractFeePerKb := calcFeePerKb(b.contractFee, b.contractTx.SerializeSize())
var contractBuf bytes.Buffer
contractBuf.Grow(b.contractTx.SerializeSize())
b.contractTx.Serialize(&contractBuf)
strContractTx := hex.EncodeToString(contractBuf.Bytes())
var contractTxHash chainhash.Hash
contractTxHash = b.contractTx.TxHash()
strContractTxHash := contractTxHash.String()
var result = &libs.ParticipateResult{}
result.Contract = hex.EncodeToString(b.contract)
result.ContractP2SH = b.contractP2SH.EncodeAddress()
result.ContractTx = strContractTx
result.ContractTxHash = strContractTxHash
result.ContractFee = int64(b.contractFee)
result.ContractFeePerKb = contractFeePerKb
result.ContractRefundLocktime = locktime
return result, nil
}