summaryrefslogtreecommitdiff
path: root/data/transactions/logic/crypto.go
blob: c5c39b654c2787c0d1acdc125b4d4dcdc6cff7ba (plain)
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
// Copyright (C) 2019-2024 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand.  If not, see <https://www.gnu.org/licenses/>.

package logic

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/sha256"
	"crypto/sha512"
	"errors"
	"fmt"
	"math/big"

	"github.com/algorand/go-algorand/crypto"
	"github.com/algorand/go-algorand/crypto/secp256k1"
	"github.com/algorand/go-algorand/protocol"
	"github.com/algorand/go-sumhash"
	"golang.org/x/crypto/sha3"
)

func opSHA256(cx *EvalContext) error {
	last := len(cx.Stack) - 1
	hash := sha256.Sum256(cx.Stack[last].Bytes)
	cx.Stack[last].Bytes = hash[:]
	return nil
}

// The NIST SHA3-256 is implemented for compatibility with ICON
func opSHA3_256(cx *EvalContext) error {
	last := len(cx.Stack) - 1
	hash := sha3.Sum256(cx.Stack[last].Bytes)
	cx.Stack[last].Bytes = hash[:]
	return nil
}

// The Keccak256 variant of SHA-3 is implemented for compatibility with Ethereum
func opKeccak256(cx *EvalContext) error {
	last := len(cx.Stack) - 1
	hasher := sha3.NewLegacyKeccak256()
	hasher.Write(cx.Stack[last].Bytes)
	hv := make([]byte, 0, hasher.Size())
	hv = hasher.Sum(hv)
	cx.Stack[last].Bytes = hv
	return nil
}

// This is the hash commonly used in Algorand in crypto/util.go Hash()
//
// It is explicitly implemented here in terms of the specific hash for
// stability and portability in case the rest of Algorand ever moves
// to a different default hash. For stability of this language, at
// that time a new opcode should be made with the new hash.
func opSHA512_256(cx *EvalContext) error {
	last := len(cx.Stack) - 1
	hash := sha512.Sum512_256(cx.Stack[last].Bytes)
	cx.Stack[last].Bytes = hash[:]
	return nil
}

// Sumhash512 corresponds to the hash used in State Proofs
func opSumhash512(cx *EvalContext) error {
	last := len(cx.Stack) - 1
	h := sumhash.New512(nil)
	h.Write(cx.Stack[last].Bytes)
	cx.Stack[last].Bytes = h.Sum(nil)
	return nil
}

func opFalconVerify(cx *EvalContext) error {
	last := len(cx.Stack) - 1 // index of PK
	prev := last - 1          // index of signature
	pprev := prev - 1         // index of data

	var fv crypto.FalconVerifier
	if len(cx.Stack[last].Bytes) != len(fv.PublicKey) {
		return fmt.Errorf("invalid public key size %d != %d", len(cx.Stack[last].Bytes), len(fv.PublicKey))
	}
	copy(fv.PublicKey[:], cx.Stack[last].Bytes)

	sig := crypto.FalconSignature(cx.Stack[prev].Bytes)

	err := fv.VerifyBytes(cx.Stack[pprev].Bytes, sig)
	cx.Stack[pprev] = boolToSV(err == nil)
	cx.Stack = cx.Stack[:prev]
	return nil
}

// Msg is data meant to be signed and then verified with the
// ed25519verify opcode.
type Msg struct {
	_struct     struct{}      `codec:",omitempty,omitemptyarray"`
	ProgramHash crypto.Digest `codec:"p"`
	Data        []byte        `codec:"d"`
}

// ToBeHashed implements crypto.Hashable
func (msg Msg) ToBeHashed() (protocol.HashID, []byte) {
	return protocol.ProgramData, append(msg.ProgramHash[:], msg.Data...)
}

// programHash lets us lazily compute H(cx.program)
func (cx *EvalContext) programHash() crypto.Digest {
	if cx.programHashCached == (crypto.Digest{}) {
		cx.programHashCached = crypto.HashObj(Program(cx.program))
	}
	return cx.programHashCached
}

func opEd25519Verify(cx *EvalContext) error {
	last := len(cx.Stack) - 1 // index of PK
	prev := last - 1          // index of signature
	pprev := prev - 1         // index of data

	var sv crypto.SignatureVerifier
	if len(cx.Stack[last].Bytes) != len(sv) {
		return errors.New("invalid public key")
	}
	copy(sv[:], cx.Stack[last].Bytes)

	var sig crypto.Signature
	if len(cx.Stack[prev].Bytes) != len(sig) {
		return errors.New("invalid signature")
	}
	copy(sig[:], cx.Stack[prev].Bytes)

	msg := Msg{ProgramHash: cx.programHash(), Data: cx.Stack[pprev].Bytes}
	cx.Stack[pprev] = boolToSV(sv.Verify(msg, sig))
	cx.Stack = cx.Stack[:prev]
	return nil
}

func opEd25519VerifyBare(cx *EvalContext) error {
	last := len(cx.Stack) - 1 // index of PK
	prev := last - 1          // index of signature
	pprev := prev - 1         // index of data

	var sv crypto.SignatureVerifier
	if len(cx.Stack[last].Bytes) != len(sv) {
		return errors.New("invalid public key")
	}
	copy(sv[:], cx.Stack[last].Bytes)

	var sig crypto.Signature
	if len(cx.Stack[prev].Bytes) != len(sig) {
		return errors.New("invalid signature")
	}
	copy(sig[:], cx.Stack[prev].Bytes)

	cx.Stack[pprev] = boolToSV(sv.VerifyBytes(cx.Stack[pprev].Bytes, sig))
	cx.Stack = cx.Stack[:prev]
	return nil
}

func leadingZeros(size int, b *big.Int) ([]byte, error) {
	byteLength := (b.BitLen() + 7) / 8
	if size < byteLength {
		return nil, fmt.Errorf("insufficient buffer size: %d < %d", size, byteLength)
	}
	buf := make([]byte, size)
	b.FillBytes(buf)
	return buf, nil
}

var ecdsaVerifyCosts = []int{
	Secp256k1: 1700,
	Secp256r1: 2500,
}

var secp256r1 = elliptic.P256()

func opEcdsaVerify(cx *EvalContext) error {
	ecdsaCurve := EcdsaCurve(cx.program[cx.pc+1])
	fs, ok := ecdsaCurveSpecByField(ecdsaCurve)
	if !ok || fs.version > cx.version {
		return fmt.Errorf("invalid curve %d", ecdsaCurve)
	}

	if fs.field != Secp256k1 && fs.field != Secp256r1 {
		return fmt.Errorf("unsupported curve %d", fs.field)
	}

	last := len(cx.Stack) - 1 // index of PK y
	prev := last - 1          // index of PK x
	pprev := prev - 1         // index of signature s
	fourth := pprev - 1       // index of signature r
	fifth := fourth - 1       // index of data

	pkY := cx.Stack[last].Bytes
	pkX := cx.Stack[prev].Bytes
	sigS := cx.Stack[pprev].Bytes
	sigR := cx.Stack[fourth].Bytes
	msg := cx.Stack[fifth].Bytes

	if len(msg) != 32 {
		return fmt.Errorf("the signed data must be 32 bytes long, not %d", len(msg))
	}

	x := new(big.Int).SetBytes(pkX)
	y := new(big.Int).SetBytes(pkY)

	var result bool
	if fs.field == Secp256k1 {
		signature := make([]byte, 0, len(sigR)+len(sigS))
		signature = append(signature, sigR...)
		signature = append(signature, sigS...)

		pubkey := secp256k1.S256().Marshal(x, y)
		result = secp256k1.VerifySignature(pubkey, msg, signature)
	} else if fs.field == Secp256r1 {
		if !cx.Proto.EnablePrecheckECDSACurve || secp256r1.IsOnCurve(x, y) {
			pubkey := ecdsa.PublicKey{
				Curve: secp256r1,
				X:     x,
				Y:     y,
			}
			r := new(big.Int).SetBytes(sigR)
			s := new(big.Int).SetBytes(sigS)
			result = ecdsa.Verify(&pubkey, msg, r, s)
		}
	}

	cx.Stack[fifth] = boolToSV(result)
	cx.Stack = cx.Stack[:fourth]
	return nil
}

var ecdsaDecompressCosts = []int{
	Secp256k1: 650,
	Secp256r1: 2400,
}

func opEcdsaPkDecompress(cx *EvalContext) error {
	ecdsaCurve := EcdsaCurve(cx.program[cx.pc+1])
	fs, ok := ecdsaCurveSpecByField(ecdsaCurve)
	if !ok || fs.version > cx.version {
		return fmt.Errorf("invalid curve %d", ecdsaCurve)
	}

	if fs.field != Secp256k1 && fs.field != Secp256r1 {
		return fmt.Errorf("unsupported curve %d", fs.field)
	}

	last := len(cx.Stack) - 1 // compressed PK

	pubkey := cx.Stack[last].Bytes
	var x, y *big.Int
	if fs.field == Secp256k1 {
		x, y = secp256k1.DecompressPubkey(pubkey)
		if x == nil {
			return fmt.Errorf("invalid pubkey")
		}
	} else if fs.field == Secp256r1 {
		x, y = elliptic.UnmarshalCompressed(elliptic.P256(), pubkey)
		if x == nil {
			return fmt.Errorf("invalid compressed pubkey")
		}
	}

	var err error
	cx.Stack[last].Uint = 0
	cx.Stack[last].Bytes, err = leadingZeros(32, x)
	if err != nil {
		return fmt.Errorf("x component zeroing failed: %w", err)
	}

	var sv stackValue
	sv.Bytes, err = leadingZeros(32, y)
	if err != nil {
		return fmt.Errorf("y component zeroing failed: %w", err)
	}

	cx.Stack = append(cx.Stack, sv)
	return nil
}

func opEcdsaPkRecover(cx *EvalContext) error {
	ecdsaCurve := EcdsaCurve(cx.program[cx.pc+1])
	fs, ok := ecdsaCurveSpecByField(ecdsaCurve)
	if !ok || fs.version > cx.version {
		return fmt.Errorf("invalid curve %d", ecdsaCurve)
	}

	if fs.field != Secp256k1 {
		return fmt.Errorf("unsupported curve %d", fs.field)
	}

	last := len(cx.Stack) - 1 // index of signature s
	prev := last - 1          // index of signature r
	pprev := prev - 1         // index of recovery id
	fourth := pprev - 1       // index of data

	sigS := cx.Stack[last].Bytes
	sigR := cx.Stack[prev].Bytes
	recid := cx.Stack[pprev].Uint
	msg := cx.Stack[fourth].Bytes

	if recid > 3 {
		return fmt.Errorf("invalid recovery id: %d", recid)
	}

	signature := make([]byte, 0, len(sigR)+len(sigS)+1)
	signature = append(signature, sigR...)
	signature = append(signature, sigS...)
	signature = append(signature, uint8(recid))

	pk, err := secp256k1.RecoverPubkey(msg, signature)
	if err != nil {
		return fmt.Errorf("pubkey recover failed: %s", err.Error())
	}
	x, y := secp256k1.S256().Unmarshal(pk)
	if x == nil {
		return fmt.Errorf("pubkey unmarshal failed")
	}

	cx.Stack[fourth].Uint = 0
	cx.Stack[fourth].Bytes, err = leadingZeros(32, x)
	if err != nil {
		return fmt.Errorf("x component zeroing failed: %s", err.Error())
	}
	cx.Stack[pprev].Uint = 0
	cx.Stack[pprev].Bytes, err = leadingZeros(32, y)
	if err != nil {
		return fmt.Errorf("y component zeroing failed: %s", err.Error())
	}
	cx.Stack = cx.Stack[:prev]
	return nil
}

type rawMessage []byte

func (rm rawMessage) ToBeHashed() (protocol.HashID, []byte) {
	return "", []byte(rm)
}

func opVrfVerify(cx *EvalContext) error {
	last := len(cx.Stack) - 1 // PK
	prev := last - 1          // proof
	pprev := prev - 1         // data

	data := rawMessage(cx.Stack[pprev].Bytes)
	proofbytes := cx.Stack[prev].Bytes
	var proof crypto.VrfProof
	if len(proofbytes) != len(proof) {
		return fmt.Errorf("vrf proof wrong size %d != %d", len(proofbytes), len(proof))
	}
	copy(proof[:], proofbytes[:])

	pubkeybytes := cx.Stack[last].Bytes
	var pubkey crypto.VrfPubkey
	if len(pubkeybytes) != len(pubkey) {
		return fmt.Errorf("vrf pubkey wrong size %d != %d", len(pubkeybytes), len(pubkey))
	}
	copy(pubkey[:], pubkeybytes[:])

	var verified bool
	var output []byte
	std := VrfStandard(cx.program[cx.pc+1])
	ss, ok := vrfStandardSpecByField(std)
	if !ok || ss.version > cx.version {
		return fmt.Errorf("invalid VRF standard %s", std)
	}
	switch std {
	case VrfAlgorand:
		var out crypto.VrfOutput
		verified, out = pubkey.Verify(proof, data)
		output = out[:]
	default:
		return fmt.Errorf("unsupported vrf_verify standard %s", std)
	}

	cx.Stack[pprev].Bytes = output[:]
	cx.Stack[prev] = boolToSV(verified)
	cx.Stack = cx.Stack[:last] // pop 1 because we take 3 args and return 2
	return nil
}