-
Notifications
You must be signed in to change notification settings - Fork 3
/
covenant.go
364 lines (310 loc) · 9.18 KB
/
covenant.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
package htlcbch
import (
"encoding/binary"
"encoding/hex"
"fmt"
gethcmn "github.com/ethereum/go-ethereum/common"
"github.com/gcash/bchd/bchec"
"github.com/gcash/bchd/chaincfg"
"github.com/gcash/bchd/txscript"
"github.com/gcash/bchd/wire"
"github.com/gcash/bchutil"
)
const (
// cashc --hex ../atomic-swap-covenants/covenants/HTLC4.cash
RedeemScriptWithoutConstructorArgsHex = "0x5579009c63c0009d567aa8537a880376a9147b7e0288ac7e00cd8800cc00c602d00794a2696d6d5167557a519dc0009d537ab27500c67600567900a06352795779950210279677527978947b757c0376a91455797e0288ac7e51cd788851cc5279a26975680376a914547a7e0288ac7e00cd8800cc7b02d00794a2696d6d755168"
)
var (
redeemScriptWithoutConstructorArgs = gethcmn.FromHex(RedeemScriptWithoutConstructorArgsHex)
)
type InputInfo struct {
TxID []byte
Vout uint32
Amount int64
}
type HtlcCovenant struct {
senderPkh []byte // 20 bytes
recipientPkh []byte // 20 bytes
hashLock []byte // 32 bytes
expiration uint16
penaltyBPS uint16
net *chaincfg.Params
}
func NewMainnetCovenant(
senderPkh, recipientPkh, hashLock []byte, expiration, penaltyBPS uint16,
) (*HtlcCovenant, error) {
return NewCovenant(senderPkh, recipientPkh, hashLock, expiration, penaltyBPS,
&chaincfg.MainNetParams)
}
func NewTestnet3Covenant(
senderPkh, recipientPkh, hashLock []byte, expiration, penaltyBPS uint16,
) (*HtlcCovenant, error) {
return NewCovenant(senderPkh, recipientPkh, hashLock, expiration, penaltyBPS,
&chaincfg.TestNet3Params)
}
func NewCovenant(
senderPkh, recipientPkh, hashLock []byte, expiration, penaltyBPS uint16,
net *chaincfg.Params,
) (*HtlcCovenant, error) {
if len(senderPkh) != 20 {
return nil, fmt.Errorf("senderPkh is not 20 bytes")
}
if len(recipientPkh) != 20 {
return nil, fmt.Errorf("recipientPkh is not 20 bytes")
}
if len(hashLock) != 32 {
return nil, fmt.Errorf("hashLock is not 32 bytes")
}
return &HtlcCovenant{
senderPkh: senderPkh,
recipientPkh: recipientPkh,
hashLock: hashLock,
expiration: expiration,
penaltyBPS: penaltyBPS,
net: net,
}, nil
}
func (c *HtlcCovenant) String() string {
return "HtlcCovenant {" +
"senderPkh: " + hex.EncodeToString(c.senderPkh) +
", recipientPkh: " + hex.EncodeToString(c.recipientPkh) +
", hashLock: " + hex.EncodeToString(c.hashLock) +
", expiration: " + fmt.Sprintf("%d", c.expiration) +
", penaltyBPS: " + fmt.Sprintf("%d", c.penaltyBPS) +
"}"
}
func (c *HtlcCovenant) GetRedeemScriptHash() ([]byte, error) {
redeemScript, err := c.BuildFullRedeemScript()
if err != nil {
return nil, err
}
return bchutil.Hash160(redeemScript), nil
}
func (c *HtlcCovenant) GetP2SHAddress() (string, error) {
redeemScript, err := c.BuildFullRedeemScript()
if err != nil {
return "", err
}
redeemHash := bchutil.Hash160(redeemScript)
addr, err := bchutil.NewAddressScriptHashFromHash(redeemHash, c.net)
if err != nil {
return "", err
}
return c.net.CashAddressPrefix + ":" + addr.EncodeAddress(), nil
}
func (c *HtlcCovenant) MakeReceiveTx(
txid []byte, vout uint32, inAmt int64, // input info
minerFeeRate uint64,
secret []byte,
) (*wire.MsgTx, error) {
// estimate miner fee
tx, err := c.makeReceiveTx(txid, vout, inAmt, secret, 1000)
if err != nil {
return nil, err
}
// make tx
minerFee := int64(len(MsgTxToBytes(tx))) * int64(minerFeeRate)
return c.makeReceiveTx(txid, vout, inAmt, secret, minerFee)
}
func (c *HtlcCovenant) MakeRefundTx(
txid []byte, vout uint32, inAmt int64, // input info
minerFeeRate uint64,
) (*wire.MsgTx, error) {
// estimate miner fee
tx, err := c.makeRefundTx(txid, vout, inAmt, 1000)
if err != nil {
return nil, err
}
// make tx
minerFee := int64(len(MsgTxToBytes(tx))) * int64(minerFeeRate)
return c.makeRefundTx(txid, vout, inAmt, minerFee)
}
func (c *HtlcCovenant) makeReceiveTx(
txid []byte, vout uint32, inAmt int64, // input info
secret []byte,
minerFee int64,
) (*wire.MsgTx, error) {
if len(secret) != 32 {
return nil, fmt.Errorf("secret is not 32 bytes")
}
seq := uint32(0)
sigScript, err := c.BuildReceiveSigScript(secret)
if err != nil {
return nil, err
}
toAddr, err := bchutil.NewAddressPubKeyHash(c.recipientPkh, c.net)
if err != nil {
return nil, err
}
return newMsgTxBuilder().
addInput(txid, vout, seq, sigScript).
addOutput(toAddr, inAmt-minerFee).
build()
}
func (c *HtlcCovenant) makeRefundTx(
txid []byte, vout uint32, inAmt int64, // input info
minerFee int64,
) (*wire.MsgTx, error) {
seq := uint32(c.expiration)
sigScript, err := c.BuildRefundSigScript()
if err != nil {
return nil, err
}
senderAddr, err := bchutil.NewAddressPubKeyHash(c.senderPkh, c.net)
if err != nil {
return nil, err
}
// no penalty
if c.penaltyBPS == 0 {
return newMsgTxBuilder().
addInput(txid, vout, seq, sigScript).
addOutput(senderAddr, inAmt-minerFee).
build()
}
// consider penalty
recipientAddr, err := bchutil.NewAddressPubKeyHash(c.recipientPkh, c.net)
if err != nil {
return nil, err
}
penaltyVal := inAmt * int64(c.penaltyBPS) / 10000
if penaltyVal < 546 {
penaltyVal = 546
}
return newMsgTxBuilder().
addInput(txid, vout, seq, sigScript).
addOutput(senderAddr, inAmt-penaltyVal-minerFee).
addOutput(recipientAddr, penaltyVal).
build()
}
func (c *HtlcCovenant) MakeLockTx(
fromKey *bchec.PrivateKey,
inputs []InputInfo, // inputs info
outAmt int64, // output info
minerFeeRate uint64,
) (*wire.MsgTx, error) {
// estimate miner fee
tx, err := c.makeLockTx(fromKey, inputs, outAmt, 1000)
if err != nil {
return nil, err
}
// make tx
minerFee := int64(len(MsgTxToBytes(tx))) * int64(minerFeeRate)
return c.makeLockTx(fromKey, inputs, outAmt, minerFee)
}
func (c *HtlcCovenant) makeLockTx(
fromKey *bchec.PrivateKey,
inputs []InputInfo, // inputs info
outAmt int64, // output info
minerFee int64,
) (*wire.MsgTx, error) {
fromPk := fromKey.PubKey().SerializeCompressed()
fromPkh := bchutil.Hash160(fromPk)
script, err := c.BuildFullRedeemScript()
if err != nil {
return nil, fmt.Errorf("failed to build full redeem script: %d", err)
}
toAddr, err := bchutil.NewAddressScriptHash(script, c.net)
if err != nil {
return nil, fmt.Errorf("failed to calc p2sh address: %d", err)
}
changeAddr, err := bchutil.NewAddressPubKeyHash(fromPkh, c.net)
if err != nil {
return nil, fmt.Errorf("failed to calc p2pkh address: %w", err)
}
prevPkScript, err := payToPubKeyHashPkScript(fromPkh)
if err != nil {
return nil, fmt.Errorf("failed to creatte pkScript: %w", err)
}
opRetScript, err := c.BuildOpRetPkScript(make([]byte, 20))
if err != nil {
return nil, fmt.Errorf("failed to build OP_RETURN: %w", err)
}
sigScriptFn := func(sig []byte) ([]byte, error) {
return payToPubKeyHashSigScript(sig, fromPk)
}
builder := newMsgTxBuilder()
var totalInAmt int64
for _, input := range inputs {
builder.addInput(input.TxID, input.Vout, 0, nil)
totalInAmt += input.Amount
}
changeAmt := totalInAmt - outAmt - minerFee
if changeAmt < 0 {
return nil, fmt.Errorf("insufficient input value: %d < %d", totalInAmt, outAmt+minerFee)
}
builder.addOutput(toAddr, outAmt)
builder.addOpRet(opRetScript)
builder.addChange(changeAddr, changeAmt)
for i, utxo := range inputs {
builder.sign(i, utxo.Amount, prevPkScript, fromKey, sigScriptFn)
}
return builder.build()
}
func (c *HtlcCovenant) BuildFullRedeemScript() ([]byte, error) {
return txscript.NewScriptBuilder().
AddInt64(int64(c.penaltyBPS)).
AddInt64(int64(c.expiration)).
AddData(c.hashLock).
AddData(c.recipientPkh).
AddData(c.senderPkh).
AddOps(redeemScriptWithoutConstructorArgs).
Script()
}
func (c *HtlcCovenant) BuildReceiveSigScript(secret []byte) ([]byte, error) {
redeemScript, err := c.BuildFullRedeemScript()
if err != nil {
return nil, err
}
return txscript.NewScriptBuilder().
AddData(secret).
AddInt64(0). // selector
AddData(redeemScript).
Script()
}
func (c *HtlcCovenant) BuildRefundSigScript() ([]byte, error) {
redeemScript, err := c.BuildFullRedeemScript()
if err != nil {
return nil, err
}
return txscript.NewScriptBuilder().
AddInt64(1). // selector
AddData(redeemScript).
Script()
}
// OP_RETURN "SBAS" <recipient pkh> <sender pkh> <hash lock> <expiration> <penalty bps> <sbch user address>
func (c *HtlcCovenant) BuildOpRetPkScript(sbchUserAddr []byte) ([]byte, error) {
return txscript.NewScriptBuilder().
AddOp(txscript.OP_RETURN).
AddData([]byte(protoID)).
AddData(c.recipientPkh).
AddData(c.senderPkh).
AddData(c.hashLock).
AddData(encodeBE16(c.expiration)).
AddData(encodeBE16(c.penaltyBPS)).
AddData(sbchUserAddr).
Script()
}
func encodeBE16(n uint16) []byte {
buf := [2]byte{}
binary.BigEndian.PutUint16(buf[:], n)
return buf[:]
}
func payToPubKeyHashSigScript(sig, pk []byte) ([]byte, error) {
return txscript.NewScriptBuilder().AddData(sig).AddData(pk).Script()
}
func payToPubKeyHashPkScript(pubKeyHash []byte) ([]byte, error) {
return txscript.NewScriptBuilder().
AddOp(txscript.OP_DUP).
AddOp(txscript.OP_HASH160).
AddData(pubKeyHash).
AddOp(txscript.OP_EQUALVERIFY).
AddOp(txscript.OP_CHECKSIG).
Script()
}
//func payToScriptHashPkScript(scriptHash []byte) ([]byte, error) {
// return txscript.NewScriptBuilder().
// AddOp(txscript.OP_HASH160).
// AddData(scriptHash).
// AddOp(txscript.OP_EQUAL).
// Script()
//}