-
Notifications
You must be signed in to change notification settings - Fork 8
/
relayer.go
395 lines (345 loc) · 10.9 KB
/
relayer.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
package bitcoinda
import (
"bytes"
"fmt"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/schnorr"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/rpcclient"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
)
// PROTOCOL_ID allows data identification by looking at the first few bytes
var PROTOCOL_ID = []byte{0x72, 0x6f, 0x6c, 0x6c}
// Sample data and keys for testing.
// bob key pair is used for signing reveal tx
// internal key pair is used for tweaking
var (
bobPrivateKey = "5JoQtsKQuH8hC9MyvfJAqo6qmKLm8ePYNucs7tPu2YxG12trzBt"
internalPrivateKey = "5JGgKfRy6vEcWBpLJV5FXUfMGNXzvdWzQHUM1rVLEUJfvZUSwvS"
)
// chunkSlice splits input slice into max chunkSize length slices
func chunkSlice(slice []byte, chunkSize int) [][]byte {
var chunks [][]byte
for i := 0; i < len(slice); i += chunkSize {
end := i + chunkSize
// necessary check to avoid slicing beyond
// slice capacity
if end > len(slice) {
end = len(slice)
}
chunks = append(chunks, slice[i:end])
}
return chunks
}
// createTaprootAddress returns an address committing to a Taproot script with
// a single leaf containing the spend path with the script:
// <embedded data> OP_DROP <pubkey> OP_CHECKSIG
func createTaprootAddress(embeddedData []byte) (string, error) {
privKey, err := btcutil.DecodeWIF(bobPrivateKey)
if err != nil {
return "", fmt.Errorf("error decoding bob private key: %w", err)
}
pubKey := privKey.PrivKey.PubKey()
// Step 1: Construct the Taproot script with one leaf.
builder := txscript.NewScriptBuilder()
builder.AddOp(txscript.OP_0)
builder.AddOp(txscript.OP_IF)
chunks := chunkSlice(embeddedData, 520)
for _, chunk := range chunks {
builder.AddData(chunk)
}
builder.AddOp(txscript.OP_ENDIF)
builder.AddData(schnorr.SerializePubKey(pubKey))
builder.AddOp(txscript.OP_CHECKSIG)
pkScript, err := builder.Script()
if err != nil {
return "", fmt.Errorf("error building script: %w", err)
}
tapLeaf := txscript.NewBaseTapLeaf(pkScript)
tapScriptTree := txscript.AssembleTaprootScriptTree(tapLeaf)
internalPrivKey, err := btcutil.DecodeWIF(internalPrivateKey)
if err != nil {
return "", fmt.Errorf("error decoding internal private key: %w", err)
}
internalPubKey := internalPrivKey.PrivKey.PubKey()
// Step 2: Generate the Taproot tree.
tapScriptRootHash := tapScriptTree.RootNode.TapHash()
outputKey := txscript.ComputeTaprootOutputKey(
internalPubKey, tapScriptRootHash[:],
)
// Step 3: Generate the Bech32m address.
address, err := btcutil.NewAddressTaproot(
schnorr.SerializePubKey(outputKey), &chaincfg.RegressionNetParams)
if err != nil {
return "", fmt.Errorf("error encoding Taproot address: %w", err)
}
return address.String(), nil
}
// payToTaprootScript creates a pk script for a pay-to-taproot output key.
func payToTaprootScript(taprootKey *btcec.PublicKey) ([]byte, error) {
return txscript.NewScriptBuilder().
AddOp(txscript.OP_1).
AddData(schnorr.SerializePubKey(taprootKey)).
Script()
}
// Relayer is a bitcoin client wrapper which provides reader and writer methods
// to write binary blobs to the blockchain.
type Relayer struct {
client *rpcclient.Client
}
// close shuts down the client.
func (r Relayer) close() { // nolint:unused
r.client.Shutdown()
}
// commitTx commits an output to the given taproot address, such that the
// output is only spendable by posting the embedded data on chain, as part of
// the script satisfying the tapscript spend path that commits to the data. It
// returns the hash of the commit transaction and error, if any.
func (r Relayer) commitTx(addr string) (*chainhash.Hash, error) {
// Create a transaction that sends 0.001 BTC to the given address.
address, err := btcutil.DecodeAddress(addr, &chaincfg.RegressionNetParams)
if err != nil {
return nil, fmt.Errorf("error decoding recipient address: %w", err)
}
amount, err := btcutil.NewAmount(0.001)
if err != nil {
return nil, fmt.Errorf("error creating new amount: %w", err)
}
hash, err := r.client.SendToAddress(address, amount)
if err != nil {
return nil, fmt.Errorf("error sending to address: %w", err)
}
return hash, nil
}
// revealTx spends the output from the commit transaction and as part of the
// script satisfying the tapscript spend path, posts the embedded data on
// chain. It returns the hash of the reveal transaction and error, if any.
func (r Relayer) revealTx(embeddedData []byte, commitHash *chainhash.Hash) (*chainhash.Hash, error) {
rawCommitTx, err := r.client.GetRawTransaction(commitHash)
if err != nil {
return nil, fmt.Errorf("error getting raw commit tx: %w", err)
}
// TODO: use a better way to find our output
var commitIndex int
var commitOutput *wire.TxOut
for i, out := range rawCommitTx.MsgTx().TxOut {
if out.Value == 100000 {
commitIndex = i
commitOutput = out
break
}
}
privKey, err := btcutil.DecodeWIF(bobPrivateKey)
if err != nil {
return nil, fmt.Errorf("error decoding bob private key: %w", err)
}
pubKey := privKey.PrivKey.PubKey()
internalPrivKey, err := btcutil.DecodeWIF(internalPrivateKey)
if err != nil {
return nil, fmt.Errorf("error decoding internal private key: %w", err)
}
internalPubKey := internalPrivKey.PrivKey.PubKey()
// Our script will be a simple <embedded-data> OP_DROP OP_CHECKSIG as the
// sole leaf of a tapscript tree.
builder := txscript.NewScriptBuilder()
builder.AddOp(txscript.OP_0)
builder.AddOp(txscript.OP_IF)
chunks := chunkSlice(embeddedData, 520)
for _, chunk := range chunks {
builder.AddData(chunk)
}
builder.AddOp(txscript.OP_ENDIF)
builder.AddData(schnorr.SerializePubKey(pubKey))
builder.AddOp(txscript.OP_CHECKSIG)
pkScript, err := builder.Script()
if err != nil {
return nil, fmt.Errorf("error building script: %w", err)
}
tapLeaf := txscript.NewBaseTapLeaf(pkScript)
tapScriptTree := txscript.AssembleTaprootScriptTree(tapLeaf)
ctrlBlock := tapScriptTree.LeafMerkleProofs[0].ToControlBlock(
internalPubKey,
)
tapScriptRootHash := tapScriptTree.RootNode.TapHash()
outputKey := txscript.ComputeTaprootOutputKey(
internalPubKey, tapScriptRootHash[:],
)
p2trScript, err := payToTaprootScript(outputKey)
if err != nil {
return nil, fmt.Errorf("error building p2tr script: %w", err)
}
tx := wire.NewMsgTx(2)
tx.AddTxIn(&wire.TxIn{
PreviousOutPoint: wire.OutPoint{
Hash: *rawCommitTx.Hash(),
Index: uint32(commitIndex), // nolint:gosec
},
})
txOut := &wire.TxOut{
Value: 1e3, PkScript: p2trScript,
}
tx.AddTxOut(txOut)
inputFetcher := txscript.NewCannedPrevOutputFetcher(
commitOutput.PkScript,
commitOutput.Value,
)
sigHashes := txscript.NewTxSigHashes(tx, inputFetcher)
sig, err := txscript.RawTxInTapscriptSignature(
tx, sigHashes, 0, txOut.Value,
txOut.PkScript, tapLeaf, txscript.SigHashDefault,
privKey.PrivKey,
)
if err != nil {
return nil, fmt.Errorf("error signing tapscript: %w", err)
}
// Now that we have the sig, we'll make a valid witness
// including the control block.
ctrlBlockBytes, err := ctrlBlock.ToBytes()
if err != nil {
return nil, fmt.Errorf("error including control block: %w", err)
}
tx.TxIn[0].Witness = wire.TxWitness{
sig, pkScript, ctrlBlockBytes,
}
hash, err := r.client.SendRawTransaction(tx, false)
if err != nil {
return nil, fmt.Errorf("error sending reveal transaction: %w", err)
}
return hash, nil
}
// Config is the relayer config
type Config struct {
Host string
User string
Pass string
HTTPPostMode bool
DisableTLS bool
}
// NewRelayer returns a new relayer. It can error if there's an RPC connection
// error with the connection config.
func NewRelayer(config Config) (*Relayer, error) {
// Set up the connection to the btcd RPC server.
// NOTE: for testing bitcoind can be used in regtest with the following params -
// bitcoind -chain=regtest -rpcport=18332 -rpcuser=rpcuser -rpcpassword=rpcpass -fallbackfee=0.000001 -txindex=1
connCfg := &rpcclient.ConnConfig{
Host: config.Host,
User: config.User,
Pass: config.Pass,
HTTPPostMode: config.HTTPPostMode,
DisableTLS: config.DisableTLS,
}
client, err := rpcclient.New(connCfg, nil)
if err != nil {
return nil, fmt.Errorf("error creating btcd RPC client: %w", err)
}
return &Relayer{
client: client,
}, nil
}
// ReadTransaction reads a transaction from the blockchain given a hash.
func (r Relayer) ReadTransaction(hash *chainhash.Hash) ([]byte, error) {
tx, err := r.client.GetRawTransaction(hash)
if err != nil {
return nil, err
}
if len(tx.MsgTx().TxIn[0].Witness) > 1 {
witness := tx.MsgTx().TxIn[0].Witness[1]
pushData, err := ExtractPushData(0, witness)
if err != nil {
return nil, err
}
// skip PROTOCOL_ID
if pushData != nil && bytes.HasPrefix(pushData, PROTOCOL_ID) {
return pushData[4:], nil
}
}
return nil, nil
}
func (r Relayer) Read(height uint64) ([][]byte, error) {
hash, err := r.client.GetBlockHash(int64(height)) // nolint:gosec
if err != nil {
return nil, err
}
block, err := r.client.GetBlock(hash)
if err != nil {
return nil, err
}
var data [][]byte
for _, tx := range block.Transactions {
if len(tx.TxIn[0].Witness) > 1 {
witness := tx.TxIn[0].Witness[1]
pushData, err := ExtractPushData(0, witness)
if err != nil {
return nil, err
}
// skip PROTOCOL_ID
if pushData != nil && bytes.HasPrefix(pushData, PROTOCOL_ID) {
data = append(data, pushData[4:])
}
}
}
return data, nil
}
func (r Relayer) Write(data []byte) (*chainhash.Hash, error) {
data = append(PROTOCOL_ID, data...)
address, err := createTaprootAddress(data)
if err != nil {
return nil, err
}
hash, err := r.commitTx(address)
if err != nil {
return nil, err
}
hash, err = r.revealTx(data, hash)
if err != nil {
return nil, err
}
return hash, nil
}
// ExtractPushData ...
func ExtractPushData(version uint16, pkScript []byte) ([]byte, error) {
type templateMatch struct {
expectPushData bool
maxPushDatas int
opcode byte
extractedData []byte
}
var template = [6]templateMatch{
{opcode: txscript.OP_FALSE},
{opcode: txscript.OP_IF},
{expectPushData: true, maxPushDatas: 10},
{opcode: txscript.OP_ENDIF},
{expectPushData: true, maxPushDatas: 1},
{opcode: txscript.OP_CHECKSIG},
}
var templateOffset int
tokenizer := txscript.MakeScriptTokenizer(version, pkScript)
out:
for tokenizer.Next() {
// Not a rollkit script if it has more opcodes than expected in the
// template.
if templateOffset >= len(template) {
return nil, nil
}
op := tokenizer.Opcode()
tplEntry := &template[templateOffset]
if tplEntry.expectPushData {
for i := 0; i < tplEntry.maxPushDatas; i++ {
data := tokenizer.Data()
if data == nil {
break out
}
tplEntry.extractedData = append(tplEntry.extractedData, data...)
tokenizer.Next()
}
} else if op != tplEntry.opcode {
return nil, nil
}
templateOffset++
}
// TODO: skipping err checks
return template[2].extractedData, nil
}