forked from perlin-network/wavelet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtx.go
322 lines (245 loc) · 8.05 KB
/
tx.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
// Copyright (c) 2019 Perlin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package wavelet
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"math/bits"
"sort"
"github.com/perlin-network/noise/edwards25519"
"github.com/perlin-network/noise/skademlia"
"github.com/perlin-network/wavelet/log"
"github.com/perlin-network/wavelet/sys"
"github.com/pkg/errors"
"golang.org/x/crypto/blake2b"
)
type Transaction struct {
Sender AccountID // Transaction sender.
Creator AccountID // Transaction creator.
Nonce uint64
ParentIDs []TransactionID // Transactions parents.
ParentSeeds []TransactionSeed
Depth uint64 // Graph depth.
Tag sys.Tag
Payload []byte
SenderSignature Signature
CreatorSignature Signature
ID TransactionID // BLAKE2b(*).
Seed TransactionSeed // BLAKE2b(Sender || ParentIDs)
SeedLen byte // Number of prefixed zeroes of BLAKE2b(Sender || ParentIDs).
}
func NewTransaction(creator *skademlia.Keypair, tag sys.Tag, payload []byte) Transaction {
tx := Transaction{Tag: tag, Payload: payload}
var nonce [8]byte // TODO(kenta): nonce
tx.Creator = creator.PublicKey()
tx.CreatorSignature = edwards25519.Sign(creator.PrivateKey(), append(nonce[:], append([]byte{byte(tx.Tag)}, tx.Payload...)...))
return tx
}
// AttachSenderToTransaction immutably attaches sender to a transaction without modifying it in-place.
func AttachSenderToTransaction(sender *skademlia.Keypair, tx Transaction, parents ...*Transaction) Transaction {
if len(parents) > 0 {
tx.ParentIDs = make([]TransactionID, 0, len(parents))
tx.ParentSeeds = make([]TransactionSeed, 0, len(parents))
sort.Slice(parents, func(i, j int) bool {
return bytes.Compare(parents[i].ID[:], parents[j].ID[:]) < 0
})
for _, parent := range parents {
tx.ParentIDs = append(tx.ParentIDs, parent.ID)
tx.ParentSeeds = append(tx.ParentSeeds, parent.Seed)
if tx.Depth < parent.Depth {
tx.Depth = parent.Depth
}
}
tx.Depth++
}
tx.Sender = sender.PublicKey()
tx.SenderSignature = edwards25519.Sign(sender.PrivateKey(), tx.Marshal())
tx.rehash()
return tx
}
func (tx *Transaction) rehash() {
logger := log.Node()
tx.ID = blake2b.Sum256(tx.Marshal())
// Calculate the new seed.
hasher, err := blake2b.New(32, nil)
if err != nil {
logger.Fatal().Err(err).Msg("BUG: blake2b.New") // should never happen
}
_, err = hasher.Write(tx.Sender[:])
if err != nil {
logger.Fatal().Err(err).Msg("BUG: hasher.Write (1)") // should never happen
}
for _, parentSeed := range tx.ParentSeeds {
_, err = hasher.Write(parentSeed[:])
if err != nil {
logger.Fatal().Err(err).Msg("BUG: hasher.Write (2)") // should never happen
}
}
// Write 8-bit hash of transaction content to reduce conflicts.
_, err = hasher.Write(tx.ID[:1])
if err != nil {
logger.Fatal().Err(err).Msg("BUG: hasher.Write (3)") // should never happen
}
seed := hasher.Sum(nil)
copy(tx.Seed[:], seed)
tx.SeedLen = byte(prefixLen(seed))
}
func (tx Transaction) Marshal() []byte {
w := bytes.NewBuffer(make([]byte, 0, 222+(SizeTransactionID*len(tx.ParentIDs))+SizeTransactionSeed*len(tx.ParentSeeds)+len(tx.Payload)))
w.Write(tx.Sender[:])
if tx.Creator != tx.Sender {
w.WriteByte(1)
w.Write(tx.Creator[:])
} else {
w.WriteByte(0)
}
var buf [8]byte
binary.BigEndian.PutUint64(buf[:8], tx.Nonce)
w.Write(buf[:8])
w.WriteByte(byte(len(tx.ParentIDs)))
for _, parentID := range tx.ParentIDs {
w.Write(parentID[:])
}
for _, parentSeed := range tx.ParentSeeds {
w.Write(parentSeed[:])
}
binary.BigEndian.PutUint64(buf[:8], tx.Depth)
w.Write(buf[:8])
w.WriteByte(byte(tx.Tag))
binary.BigEndian.PutUint32(buf[:4], uint32(len(tx.Payload)))
w.Write(buf[:4])
w.Write(tx.Payload)
w.Write(tx.SenderSignature[:])
if tx.Creator != tx.Sender {
w.Write(tx.CreatorSignature[:])
}
return w.Bytes()
}
func UnmarshalTransaction(r io.Reader) (t Transaction, err error) {
if _, err = io.ReadFull(r, t.Sender[:]); err != nil {
err = errors.Wrap(err, "failed to decode transaction sender")
return
}
var buf [8]byte
if _, err = io.ReadFull(r, buf[:1]); err != nil {
err = errors.Wrap(err, "failed to decode flag to see if transaction creator is recorded")
return
}
if buf[0] != 0 && buf[0] != 1 {
err = errors.Errorf("flag must be zero or one, but is %d instead", buf[0])
return
}
creatorRecorded := buf[0] == 1
if !creatorRecorded {
t.Creator = t.Sender
} else {
if _, err = io.ReadFull(r, t.Creator[:]); err != nil {
err = errors.Wrap(err, "failed to decode transaction creator")
return
}
}
if _, err = io.ReadFull(r, buf[:8]); err != nil {
err = errors.Wrap(err, "failed to read nonce")
return
}
t.Nonce = binary.BigEndian.Uint64(buf[:8])
if _, err = io.ReadFull(r, buf[:1]); err != nil {
err = errors.Wrap(err, "failed to read num parents")
return
}
if int(buf[0]) > sys.MaxParentsPerTransaction {
err = errors.Errorf("tx while decoding has %d parents, but may only have at most %d parents", buf[0], sys.MaxParentsPerTransaction)
return
}
t.ParentIDs = make([]TransactionID, buf[0])
for i := range t.ParentIDs {
if _, err = io.ReadFull(r, t.ParentIDs[i][:]); err != nil {
err = errors.Wrapf(err, "failed to decode parent %d", i)
return
}
}
t.ParentSeeds = make([]TransactionSeed, len(t.ParentIDs))
for i := range t.ParentSeeds {
if _, err = io.ReadFull(r, t.ParentSeeds[i][:]); err != nil {
err = errors.Wrapf(err, "failed to decode parent seed %d", i)
return
}
}
if _, err = io.ReadFull(r, buf[:8]); err != nil {
err = errors.Wrap(err, "could not read transaction depth")
return
}
t.Depth = binary.BigEndian.Uint64(buf[:8])
if _, err = io.ReadFull(r, buf[:1]); err != nil {
err = errors.Wrap(err, "could not read transaction tag")
return
}
t.Tag = sys.Tag(buf[0])
if _, err = io.ReadFull(r, buf[:4]); err != nil {
err = errors.Wrap(err, "could not read transaction payload length")
return
}
t.Payload = make([]byte, binary.BigEndian.Uint32(buf[:4]))
if _, err = io.ReadFull(r, t.Payload[:]); err != nil {
err = errors.Wrap(err, "could not read transaction payload")
return
}
if _, err = io.ReadFull(r, t.SenderSignature[:]); err != nil {
err = errors.Wrap(err, "failed to decode signature")
return
}
if !creatorRecorded {
t.CreatorSignature = t.SenderSignature
} else {
if _, err = io.ReadFull(r, t.CreatorSignature[:]); err != nil {
err = errors.Wrap(err, "failed to decode creator signature")
return
}
}
t.rehash()
return t, nil
}
func (tx Transaction) IsCritical(difficulty byte) bool {
return tx.SeedLen >= difficulty
}
// LogicalUnits counts the total number of atomic logical units of changes
// the specified tx comprises of.
func (tx Transaction) LogicalUnits() int {
if tx.Tag != sys.TagBatch {
return 1
}
var buf [1]byte
if _, err := io.ReadFull(bytes.NewReader(tx.Payload), buf[:1]); err != nil {
return 1
}
return int(buf[0])
}
func (tx Transaction) String() string {
return fmt.Sprintf("Transaction{ID: %x}", tx.ID)
}
func prefixLen(buf []byte) int {
for i, b := range buf {
if b != 0 {
return i*8 + bits.LeadingZeros8(uint8(b))
}
}
return len(buf)*8 - 1
}