-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathtransaction_p2wpkh_v0.go
95 lines (81 loc) · 2.12 KB
/
transaction_p2wpkh_v0.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
// tokucore
//
// Copyright 2019 by KeyFuse Labs
// BSD License
package main
import (
"fmt"
"github.com/keyfuse/tokucore/xcore"
"github.com/keyfuse/tokucore/xcore/bip32"
)
func assertNil(err error) {
if err != nil {
panic(err)
}
}
// Demo for sent coin to Native SegWit P2WPKH address and spending from SegWit address to normal address.
func main() {
seed := []byte("this.is.bohu.seed.")
bohuHDKey := bip32.NewHDKey(seed)
bohuPrv := bohuHDKey.PrivateKey()
bohuPub := bohuHDKey.PublicKey()
bohu := xcore.NewPayToPubKeyHashAddress(bohuPub.Hash160())
// Satoshi.
seed = []byte("this.is.satoshi.seed.")
satoshiHDKey := bip32.NewHDKey(seed)
satoshiPrv := satoshiHDKey.PrivateKey()
satoshiPubKey := satoshiHDKey.PublicKey()
satoshi := xcore.NewPayToWitnessV0PubKeyHashAddress(satoshiPubKey.Hash160())
// Funding to SegWit.
{
bohuCoin := xcore.NewCoinBuilder().AddOutput(
"f519a75190312039ddf885231205006b14f2e69f6e5b02314cb0e367b027fa86",
1,
127297408,
"76a9145a927ddadc0ef3ae4501d0d9872b57c9584b9d8888ac",
).ToCoins()[0]
tx, err := xcore.NewTransactionBuilder().
AddCoin(bohuCoin).
AddKeys(bohuPrv).
To(satoshi, 666666).
Then().
SetChange(bohu).
SetRelayFeePerKb(20000).
Then().
Sign().
BuildTransaction()
assertNil(err)
// Verify.
err = tx.Verify()
assertNil(err)
fmt.Printf("p2wpkh.fund:%v\n", tx.ToString())
fmt.Printf("p2wpkh.fund.txid:%v\n", tx.ID())
fmt.Printf("p2wpkh.fund.tx:%x\n", tx.Serialize())
}
// Spending From SegWit.
{
satoshiCoin := xcore.NewCoinBuilder().AddOutput(
"c37c3154ae611cfd9a57e684f0c12d51491d09060c643adc292565884e947b2b",
0,
666666,
"00148b7f2212ecc4384abcf1df3fc5783e9c2a24d5a5",
).ToCoins()[0]
tx, err := xcore.NewTransactionBuilder().
AddCoin(satoshiCoin).
AddKeys(satoshiPrv).
To(bohu, 66666).
Then().
SetChange(satoshi).
SetRelayFeePerKb(20000).
Then().
Sign().
BuildTransaction()
assertNil(err)
// Verify.
err = tx.Verify()
assertNil(err)
fmt.Printf("p2wpkh.spend:%v\n", tx.ToString())
fmt.Printf("p2wpkh.spend.txid:%v\n", tx.ID())
fmt.Printf("p2wpkh.spend.tx:%x\n", tx.Serialize())
}
}