forked from utamaro/gocoin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransaction.go
248 lines (211 loc) · 6.79 KB
/
transaction.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
/*
* Copyright (c) 2015, Shinya Yagyu
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* See LICENSE file for the original license:
*/
package gocoin
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
)
//TXin represents tx input of a transaction.
type TXin struct {
Hash []byte
Index uint32
scriptSig []byte
Sequence uint32
PrevScriptPubkey []byte
CreateScriptSig func(rawTransactionHashed []byte) ([]byte, error)
}
//TXout represents tx output of a transaction.
type TXout struct {
Value uint64
ScriptPubkey []byte
}
//TX represents transaction.
type TX struct {
Txin []*TXin
Txout []*TXout
Locktime uint32
}
func (tx *TX) check() error {
if tx.Txin == nil || len(tx.Txin) == 0 {
return errors.New("txin must be filled")
} else if tx.Txout == nil || len(tx.Txout) == 0 {
return errors.New("txout must be filled")
}
for i, in := range tx.Txin {
if in.Hash == nil {
return fmt.Errorf("hash of number %d of TxIn is nil", i)
} else if in.PrevScriptPubkey == nil {
return fmt.Errorf("PrevScriptPubkey of number %d is nil", i)
}
}
for i, out := range tx.Txout {
if out.ScriptPubkey == nil {
return fmt.Errorf("ScriptPubkey of number %d of Txout is nil", i)
}
}
return nil
}
//MakeTX makes transaction and return tx hex string(not send)
func (tx *TX) MakeTX() ([]byte, error) {
var err error
if err = tx.check(); err != nil {
return nil, err
}
for i, in := range tx.Txin {
if in.CreateScriptSig == nil {
return nil, errors.New("in.CreateScriptSig must be set")
}
rawTransactionHashed := tx.getRawTransactionHash(i)
in.scriptSig, err = in.CreateScriptSig(rawTransactionHashed[:])
if err != nil {
return nil, err
}
}
//Sign the raw transaction, and output it to the console.
finalTransaction := tx.createRawTransaction(-1)
finalTransactionHex := hex.EncodeToString(finalTransaction)
logging.Println("Your final transaction is")
logging.Println(finalTransactionHex)
return finalTransaction, nil
}
func (tx *TX) getTransactionHash() ([]byte, error) {
rawtx, err := tx.MakeTX()
if err != nil {
return nil, err
}
hash := sha256.Sum256(rawtx)
h := sha256.Sum256(hash[:])
reversed := make([]byte, len(h))
for i, tb := range h {
reversed[len(h)-i-1] = tb
}
return reversed, nil
}
func (tx *TX) getRawTransactionHash(numSign int) []byte {
rawTransaction := tx.createRawTransaction(numSign)
//After completing the raw transaction, we append
//SIGHASH_ALL in little-endian format to the end of the raw transaction.
hashCodeType := []byte{0x01, 0x00, 0x00, 0x00}
var rawTransactionBuffer bytes.Buffer
rawTransactionBuffer.Write(rawTransaction)
rawTransactionBuffer.Write(hashCodeType)
rawTransactionWithHashCodeType := rawTransactionBuffer.Bytes()
//Hash the raw transaction twice before the signing
hash := sha256.Sum256(rawTransactionWithHashCodeType)
h := sha256.Sum256(hash[:])
return h[:]
}
//createRawTransaction creates a transaction from tx struct.
//if numSing>=0, this returns a transaction for singning, and
//numSign is number of txin which will be singed later.
//if numSing<0, returns a transaction for broadcast.
func (tx *TX) createRawTransaction(numSign int) []byte {
//Create the raw transaction.
var buffer bytes.Buffer
//Version field
version := []byte{0x01, 0x00, 0x00, 0x00}
buffer.Write(version)
//# of inputs
inputs := toVI(uint64(len(tx.Txin)))
buffer.Write(inputs)
for nIn, in := range tx.Txin {
//Input transaction hash
//Convert input transaction hash to little-endian form
inputTransactionBytesReversed := make([]byte, len(in.Hash))
for i, tb := range in.Hash {
inputTransactionBytesReversed[len(in.Hash)-i-1] = tb
}
buffer.Write(inputTransactionBytesReversed)
//Output index of input transaction
outputIndexBytes := make([]byte, 4)
binary.LittleEndian.PutUint32(outputIndexBytes, in.Index)
buffer.Write(outputIndexBytes)
var script []byte
switch {
case nIn == numSign:
script = in.PrevScriptPubkey
case numSign >= 0:
script = []byte{}
default:
script = in.scriptSig
}
//Script sig length
scriptSigLength := len(script)
buffer.Write(toVI(uint64(scriptSigLength)))
buffer.Write(script)
//sequence_no. Normally 0xFFFFFFFF.
seqBytes := make([]byte, 4)
binary.LittleEndian.PutUint32(seqBytes, in.Sequence)
buffer.Write(seqBytes)
}
//# of outputs
outputs := toVI(uint64(len(tx.Txout)))
buffer.Write(outputs)
for _, out := range tx.Txout {
//Satoshis to send.
satoshiBytes := make([]byte, 8)
binary.LittleEndian.PutUint64(satoshiBytes, out.Value)
buffer.Write(satoshiBytes)
//Script sig length
scriptSigLength := len(out.ScriptPubkey)
buffer.Write(toVI(uint64(scriptSigLength)))
buffer.Write(out.ScriptPubkey)
}
//Lock time field
lockTimeField := make([]byte, 4)
binary.LittleEndian.PutUint32(lockTimeField, tx.Locktime)
buffer.Write(lockTimeField)
return buffer.Bytes()
}
func toVI(n uint64) []byte {
if n < uint64(0xfd) {
b := make([]byte, 1)
b[0] = byte(n & 0xff)
return b
} else if n <= uint64(0xffff) {
b := make([]byte, 3)
b[0] = 0xfd
binary.LittleEndian.PutUint16(b[1:], uint16(n))
return b
} else if n <= uint64(0xffffffff) {
b := make([]byte, 5)
b[0] = 0xfe
binary.LittleEndian.PutUint32(b[1:], uint32(n))
return b
}
b := make([]byte, 9)
b[0] = 0xff
binary.LittleEndian.PutUint64(b[1:], n)
return b
}