This repository has been archived by the owner on Jul 20, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathsignatures.go
368 lines (330 loc) · 10.5 KB
/
signatures.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
package types
// signatures.go contains all of the types and functions related to creating
// and verifying transaction signatures. There are a lot of rules surrounding
// the correct use of signatures. Signatures can cover part or all of a
// transaction, can be multiple different algorithms, and must satify a field
// called 'UnlockConditions'.
import (
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"strings"
"github.com/threefoldtech/rivine/build"
"github.com/threefoldtech/rivine/crypto"
"github.com/threefoldtech/rivine/pkg/encoding/rivbin"
"github.com/threefoldtech/rivine/pkg/encoding/siabin"
)
// SignatureAlgoType identifies a signature algorithm as a single byte.
type SignatureAlgoType uint8
const (
// SignatureAlgoNil identifies a nil SignatureAlgoType value.
SignatureAlgoNil SignatureAlgoType = iota
// SignatureAlgoEd25519 identifies the Ed25519 signature Algorithm,
// the default (and only) algorithm supported by this chain.
SignatureAlgoEd25519
)
// These Specifiers enumerate the string versions of the types of signatures that are recognized
// by this implementation. see Consensus.md for more details.
var (
SignatureAlgoNilSpecifier = Specifier{}
SignatureAlgoEd25519Specifier = Specifier{'e', 'd', '2', '5', '5', '1', '9'}
)
func (sat SignatureAlgoType) String() string {
return sat.Specifier().String()
}
// Specifier returns the specifier linked to this Signature Algorithm Type,
// returns the SignatureAlgoNilSpecifier if the algorithm type is unknown.
func (sat SignatureAlgoType) Specifier() Specifier {
switch sat {
case SignatureAlgoEd25519:
return SignatureAlgoEd25519Specifier
default:
return SignatureAlgoNilSpecifier
}
}
// LoadString loads the stringified algo type as its single byte representation.
func (sat *SignatureAlgoType) LoadString(str string) error {
switch str {
case SignatureAlgoEd25519Specifier.String():
*sat = SignatureAlgoEd25519
case SignatureAlgoNilSpecifier.String():
*sat = SignatureAlgoNil
default:
return fmt.Errorf("unknown SignatureAlgoType string: %s", str)
}
return nil
}
// LoadSpecifier loads the algorithm type in specifier-format.
func (sat *SignatureAlgoType) LoadSpecifier(specifier Specifier) error {
switch specifier {
case SignatureAlgoEd25519Specifier:
*sat = SignatureAlgoEd25519
case SignatureAlgoNilSpecifier:
*sat = SignatureAlgoNil
default:
return fmt.Errorf("unknown SignatureAlgoType specifier: %s", specifier.String())
}
return nil
}
// Signature-related errors
var (
//ErrFrivolousSignature = errors.New("transaction contains a frivolous signature")
//ErrInvalidPubKeyIndex = errors.New("transaction contains a signature that points to a nonexistent public key")
ErrInvalidUnlockHashChecksum = errors.New("provided unlock hash has an invalid checksum")
//ErrMissingSignatures = errors.New("transaction has inputs with missing signatures")
//ErrPrematureSignature = errors.New("timelock on signature has not expired")
//ErrPublicKeyOveruse = errors.New("public key was used multiple times while signing transaction")
//ErrSortedUniqueViolation = errors.New("sorted unique violation")
ErrUnlockHashWrongLen = errors.New("marshalled unlock hash is the wrong length")
)
type (
// A PublicKey is a public key prefixed by a Specifier. The Specifier
// indicates the algorithm used for signing and verification. Unrecognized
// algorithms will always verify, which allows new algorithms to be added to
// the protocol via a soft-fork.
PublicKey struct {
Algorithm SignatureAlgoType
Key ByteSlice
}
// ByteSlice defines any kind of raw binary value,
// in-memory defined as a byte slice,
// and JSON-encoded in hexadecimal form.
ByteSlice []byte
)
// Ed25519PublicKey returns pk as a PublicKey, denoting its algorithm as
// Ed25519.
func Ed25519PublicKey(pk crypto.PublicKey) PublicKey {
return PublicKey{
Algorithm: SignatureAlgoEd25519,
Key: pk[:],
}
}
// SignatureHash returns the hash of all fields in a transaction,
// relevant to a Tx sig.
func (t Transaction) SignatureHash(extraObjects ...interface{}) (crypto.Hash, error) {
controller, exists := _RegisteredTransactionVersions[t.Version]
if !exists {
return crypto.Hash{}, ErrUnknownTransactionType
}
if hasher, ok := controller.(TransactionSignatureHasher); ok {
// if extension implements TransactionSignatureHasher,
// use it here to sign the input with it
return hasher.SignatureHash(t, extraObjects...)
}
h := crypto.NewHash()
enc := siabin.NewEncoder(h)
enc.Encode(t.Version)
if len(extraObjects) > 0 {
enc.EncodeAll(extraObjects...)
}
enc.Encode(len(t.CoinInputs))
for _, ci := range t.CoinInputs {
enc.Encode(ci.ParentID)
}
enc.Encode(t.CoinOutputs)
enc.Encode(len(t.BlockStakeInputs))
for _, bsi := range t.BlockStakeInputs {
enc.Encode(bsi.ParentID)
}
enc.EncodeAll(
t.BlockStakeOutputs,
t.MinerFees,
t.ArbitraryData,
)
var hash crypto.Hash
h.Sum(hash[:0])
return hash, nil
}
func (t Transaction) legacyInputSigHash(inputIndex uint64, extraObjects ...interface{}) crypto.Hash {
h := crypto.NewHash()
enc := siabin.NewEncoder(h)
enc.Encode(inputIndex)
if len(extraObjects) > 0 {
enc.EncodeAll(extraObjects...)
}
for _, ci := range t.CoinInputs {
enc.EncodeAll(ci.ParentID, legacyUnlockHashFromFulfillment(ci.Fulfillment.Fulfillment))
}
// legacy transactions encoded unlock hashes in pure form
enc.Encode(len(t.CoinOutputs))
for _, co := range t.CoinOutputs {
enc.EncodeAll(
co.Value,
legacyUnlockHashCondition(co.Condition.Condition),
)
}
for _, bsi := range t.BlockStakeInputs {
enc.EncodeAll(bsi.ParentID, legacyUnlockHashFromFulfillment(bsi.Fulfillment.Fulfillment))
}
// legacy transactions encoded unlock hashes in pure form
enc.Encode(len(t.BlockStakeOutputs))
for _, bso := range t.BlockStakeOutputs {
enc.EncodeAll(
bso.Value,
legacyUnlockHashCondition(bso.Condition.Condition),
)
}
enc.EncodeAll(
t.MinerFees,
t.ArbitraryData,
)
var hash crypto.Hash
h.Sum(hash[:0])
return hash
}
func legacyUnlockHashCondition(uc UnlockCondition) UnlockHash {
uhc, ok := uc.(*UnlockHashCondition)
if !ok {
build.Severe(fmt.Sprintf("unexpected condition %[1]v (%[1]T) encountered", uc))
return NilUnlockHash
}
return uhc.TargetUnlockHash
}
func legacyUnlockHashFromFulfillment(uf UnlockFulfillment) UnlockHash {
switch tuf := uf.(type) {
case *SingleSignatureFulfillment:
pkb, _ := siabin.Marshal(tuf.PublicKey)
h, _ := crypto.HashObject(pkb)
return NewUnlockHash(UnlockTypePubKey, h)
case *LegacyAtomicSwapFulfillment:
b, _ := siabin.MarshalAll(tuf.Sender, tuf.Receiver, tuf.HashedSecret, tuf.TimeLock)
h, _ := crypto.HashObject(b)
return NewUnlockHash(UnlockTypeAtomicSwap, h)
default:
build.Severe(fmt.Sprintf("unexpected fulfillment %[1]v (%[1]T) encountered", uf))
return NilUnlockHash
}
}
// sortedUnique checks that 'elems' is sorted, contains no repeats, and that no
// element is larger than or equal to 'max'.
func sortedUnique(elems []uint64, max int) bool {
if len(elems) == 0 {
return true
}
biggest := elems[0]
for _, elem := range elems[1:] {
if elem <= biggest {
return false
}
biggest = elem
}
if biggest >= uint64(max) {
return false
}
return true
}
// MarshalSia implements SiaMarshaler.MarshalSia
func (pk PublicKey) MarshalSia(w io.Writer) error {
return siabin.NewEncoder(w).EncodeAll(
pk.Algorithm.Specifier(),
pk.Key,
)
}
// UnmarshalSia implements SiaUnmarshaler.UnmarshalSia
func (pk *PublicKey) UnmarshalSia(r io.Reader) error {
// decode the algorithm type, required to know
// what length of byte slice to expect
var algoSpecifier Specifier
err := siabin.NewDecoder(r).DecodeAll(&algoSpecifier, &pk.Key)
if err != nil {
return err
}
return pk.Algorithm.LoadSpecifier(algoSpecifier)
}
// MarshalRivine implements RivineMarshaler.MarshalRivine
func (pk PublicKey) MarshalRivine(w io.Writer) error {
err := rivbin.NewEncoder(w).Encode(pk.Algorithm)
if err != nil || pk.Algorithm == SignatureAlgoNil {
return err // nil if pk.Algorithm == SignatureAlgoNil
}
l, err := w.Write([]byte(pk.Key))
if err != nil {
return err
}
if l != len(pk.Key) {
return io.ErrShortWrite
}
return nil
}
// UnmarshalRivine implements RivineUnmarshaler.UnmarshalRivine
func (pk *PublicKey) UnmarshalRivine(r io.Reader) error {
// decode the algorithm type, required to know
// what length of byte slice to expect
err := rivbin.NewDecoder(r).Decode(&pk.Algorithm)
if err != nil {
return err
}
// create the expected sized byte slice, depending on the algorithm type
switch pk.Algorithm {
case SignatureAlgoEd25519:
pk.Key = make(ByteSlice, crypto.PublicKeySize)
case SignatureAlgoNil:
pk.Key = nil
default:
return fmt.Errorf("unknown SignatureAlgoType %d", pk.Algorithm)
}
// read byte slice
_, err = io.ReadFull(r, pk.Key[:])
return err
}
// LoadString is the inverse of PublicKey.String().
func (pk *PublicKey) LoadString(s string) error {
parts := strings.SplitN(s, ":", 2)
if len(parts) != 2 {
return errors.New("invalid public key string")
}
err := pk.Key.LoadString(parts[1])
if err != nil {
return err
}
return pk.Algorithm.LoadString(parts[0])
}
// String defines how to print a PublicKey - hex is used to keep things
// compact during logging. The key type prefix and lack of a checksum help to
// separate it from a sia address.
func (pk *PublicKey) String() string {
return pk.Algorithm.String() + ":" + pk.Key.String()
}
// MarshalJSON marshals a byte slice as a hex string.
func (pk PublicKey) MarshalJSON() ([]byte, error) {
return json.Marshal(pk.String())
}
// UnmarshalJSON decodes the json string of the byte slice.
func (pk *PublicKey) UnmarshalJSON(b []byte) error {
var str string
if err := json.Unmarshal(b, &str); err != nil {
return err
}
return pk.LoadString(str)
}
// String turns this byte slice into a hex-formatted string.
func (bs ByteSlice) String() string {
return hex.EncodeToString([]byte(bs))
}
// LoadString loads a byte slice from a hex-formatted string.
func (bs *ByteSlice) LoadString(str string) error {
b, err := hex.DecodeString(str)
if err != nil {
return err
}
*bs = ByteSlice(b)
return nil
}
// MarshalJSON marshals a byte slice as a hex string.
func (bs ByteSlice) MarshalJSON() ([]byte, error) {
return json.Marshal(bs.String())
}
// UnmarshalJSON decodes the json string of the byte slice.
func (bs *ByteSlice) UnmarshalJSON(b []byte) error {
var str string
if err := json.Unmarshal(b, &str); err != nil {
return err
}
return bs.LoadString(str)
}
var (
_ json.Marshaler = ByteSlice{}
_ json.Unmarshaler = (*ByteSlice)(nil)
)