-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtx_btc.go
More file actions
76 lines (71 loc) · 1.65 KB
/
tx_btc.go
File metadata and controls
76 lines (71 loc) · 1.65 KB
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
package cryptopay
import (
"encoding/hex"
"github.com/bitgoin/address"
"github.com/bitgoin/tx"
log "github.com/golang/glog"
)
type Unspent struct {
Tx string // hex encoded transaction
N uint32 // transaction index
Amount uint64
Confirmations int
Script string
}
// receives 'from' wiff encoded private key. and the BTC address to send.
func MakeTransactionBTC(from, to string, amount, fee uint64, unspent []Unspent) ([]byte, error) {
coins, err := ToUTXO(unspent, from)
if err != nil {
log.Error(err)
return nil, err
}
//prepare send addresses and its amount.
//last address must be refund address and its amount must be 0.
send := []*tx.Send{
&tx.Send{
Addr: to,
Amount: amount,
},
&tx.Send{
Addr: "",
Amount: 0,
},
}
locktime := uint32(0)
tx, err := tx.NewP2PK(fee, coins, locktime, send...)
if err != nil {
log.Error(err)
return nil, err
}
return tx.Pack()
}
// copy from https://github.com/bitgoin/blockr/blob/master/blockr.go#L171
//ToUTXO returns utxo in transaction package.
// privs bep58
func ToUTXO(utxos []Unspent, privs string) (tx.UTXOs, error) {
//prepare private key.
priv, err := address.FromWIF(privs, address.BitcoinMain)
if err != nil {
return nil, err
}
txs := make(tx.UTXOs, len(utxos))
for i, utxo := range utxos {
hash, err := hex.DecodeString(utxo.Tx)
if err != nil {
return nil, err
}
hash = tx.Reverse(hash)
script, err := hex.DecodeString(utxo.Script)
if err != nil {
return nil, err
}
txs[i] = &tx.UTXO{
Value: utxo.Amount,
Key: priv,
TxHash: hash,
TxIndex: utxo.N,
Script: script,
}
}
return txs, nil
}