/
eth.go
executable file
·366 lines (311 loc) · 10.8 KB
/
eth.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
package models
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"math/big"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/types"
"github.com/smartcontractkit/chainlink/core/utils"
"github.com/tidwall/gjson"
"go.uber.org/multierr"
null "gopkg.in/guregu/null.v3"
)
//go:generate gencodec -type Log -field-override logMarshaling -out gen_log_json.go
// Log represents a contract log event. These events are generated by the LOG opcode and
// stored/indexed by the node.
type Log struct {
// Consensus fields:
// address of the contract that generated the event
Address common.Address `json:"address" gencodec:"required"`
// list of topics provided by the contract.
Topics []common.Hash `json:"topics" gencodec:"required"`
// supplied by the contract, usually ABI-encoded
Data []byte `json:"data" gencodec:"required"`
// Derived fields. These fields are filled in by the node
// but not secured by consensus.
// block in which the transaction was included
BlockNumber uint64 `json:"blockNumber"`
// hash of the transaction
TxHash common.Hash `json:"transactionHash"`
// index of the transaction in the block
TxIndex uint `json:"transactionIndex"`
// hash of the block in which the transaction was included
BlockHash common.Hash `json:"blockHash"`
// index of the log in the receipt
Index uint `json:"logIndex"`
// The Removed field is true if this log was reverted due to a chain reorganisation.
// You must pay attention to this field if you receive logs through a filter query.
Removed bool `json:"removed"`
}
func (log Log) getTopic(idx uint) (common.Hash, error) {
if len(log.Topics) <= int(idx) {
return common.Hash{}, fmt.Errorf("Log: Unable to get topic #%v for %v", idx, log)
}
return log.Topics[idx], nil
}
type logMarshaling struct {
Data hexutil.Bytes
BlockNumber hexutil.Uint64
TxIndex hexutil.Uint
Index hexutil.Uint
}
// Tx contains fields necessary for an Ethereum transaction with
// an additional field for the TxAttempt.
type Tx struct {
ID uint64 `gorm:"primary_key;auto_increment"`
// SurrogateID is used to look up a transaction using a secondary ID, used to
// associate jobs with transactions so that we don't double spend in certain
// failure scenarios
SurrogateID null.String `gorm:"index;unique"`
Attempts []*TxAttempt `json:"-"`
From common.Address `gorm:"index;not null"`
To common.Address `gorm:"not null"`
Data []byte `gorm:"not null"`
Nonce uint64 `gorm:"index;not null"`
Value *Big `gorm:"type:varchar(78);not null"`
GasLimit uint64 `gorm:"not null"`
// TxAttempt fields manually included; can't embed another primary_key
Hash common.Hash `gorm:"not null"`
GasPrice *Big `gorm:"type:varchar(78);not null"`
Confirmed bool `gorm:"not null"`
SentAt uint64 `gorm:"not null"`
SignedRawTx string `gorm:"type:text;not null"`
}
// String implements Stringer for Tx
func (tx *Tx) String() string {
return fmt.Sprintf("Tx{ID: %d, From: %s, To: %s, Hash: %s, SentAt: %d}",
tx.ID,
tx.From.String(),
tx.To.String(),
tx.Hash.String(),
tx.SentAt)
}
// EthTx creates a new Ethereum transaction with a given gasPrice in wei
// that is ready to be signed.
func (tx Tx) EthTx(gasPriceWei *big.Int) *types.Transaction {
return types.NewTransaction(
tx.Nonce,
tx.To,
tx.Value.ToInt(),
tx.GasLimit,
gasPriceWei,
tx.Data,
)
}
// TxAttempt is used for keeping track of transactions that
// have been written to the Ethereum blockchain. This makes
// it so that if the network is busy, a transaction can be
// resubmitted with a higher GasPrice.
type TxAttempt struct {
ID uint64 `gorm:"primary_key;auto_increment"`
TxID uint64 `gorm:"index;type:bigint REFERENCES txes(id) ON DELETE CASCADE"`
Tx *Tx `json:"-" gorm:"PRELOAD:false;foreignkey:TxID"`
CreatedAt time.Time `gorm:"index;not null"`
Hash common.Hash `gorm:"index;not null"`
GasPrice *Big `gorm:"type:varchar(78);not null"`
Confirmed bool `gorm:"not null"`
SentAt uint64 `gorm:"not null"`
SignedRawTx string `gorm:"type:text;not null"`
}
// String implements Stringer for TxAttempt
func (txa *TxAttempt) String() string {
return fmt.Sprintf("TxAttempt{ID: %d, TxID: %d, Hash: %s, SentAt: %d, Confirmed: %t}",
txa.ID,
txa.TxID,
txa.Hash.String(),
txa.SentAt,
txa.Confirmed)
}
// GetID returns the ID of this structure for jsonapi serialization.
func (txa TxAttempt) GetID() string {
return txa.Hash.Hex()
}
// GetName returns the pluralized "type" of this structure for jsonapi serialization.
func (txa TxAttempt) GetName() string {
return "txattempts"
}
// SetID is used to set the ID of this structure when deserializing from jsonapi documents.
func (txa *TxAttempt) SetID(value string) error {
txa.Hash = common.HexToHash(value)
return nil
}
// FunctionSelector is the first four bytes of the call data for a
// function call and specifies the function to be called.
type FunctionSelector [FunctionSelectorLength]byte
// FunctionSelectorLength should always be a length of 4 as a byte.
const FunctionSelectorLength = 4
// BytesToFunctionSelector converts the given bytes to a FunctionSelector.
func BytesToFunctionSelector(b []byte) FunctionSelector {
var f FunctionSelector
f.SetBytes(b)
return f
}
// HexToFunctionSelector converts the given string to a FunctionSelector.
func HexToFunctionSelector(s string) FunctionSelector {
return BytesToFunctionSelector(common.FromHex(s))
}
// String returns the FunctionSelector as a string type.
func (f FunctionSelector) String() string { return hexutil.Encode(f[:]) }
// Bytes returns the FunctionSelector as a byte slice
func (f FunctionSelector) Bytes() []byte { return f[:] }
// WithoutPrefix returns the FunctionSelector as a string without the '0x' prefix.
func (f FunctionSelector) WithoutPrefix() string { return f.String()[2:] }
// SetBytes sets the FunctionSelector to that of the given bytes (will trim).
func (f *FunctionSelector) SetBytes(b []byte) { copy(f[:], b[:FunctionSelectorLength]) }
// UnmarshalJSON parses the raw FunctionSelector and sets the FunctionSelector
// type to the given input.
func (f *FunctionSelector) UnmarshalJSON(input []byte) error {
var s string
err := json.Unmarshal(input, &s)
if err != nil {
return err
}
if utils.HasHexPrefix(s) {
bytes := common.FromHex(s)
if len(bytes) != FunctionSelectorLength {
return errors.New("Function ID must be 4 bytes in length")
}
f.SetBytes(bytes)
} else {
bytes, err := utils.Keccak256([]byte(s))
if err != nil {
return err
}
f.SetBytes(bytes[0:4])
}
return nil
}
// BlockHeader represents a block header in the Ethereum blockchain.
// Deliberately does not have required fields because some fields aren't
// present depending on the Ethereum node.
// i.e. Parity does not always send mixHash
type BlockHeader struct {
ParentHash common.Hash `json:"parentHash"`
UncleHash common.Hash `json:"sha3Uncles"`
Coinbase common.Address `json:"miner"`
Root common.Hash `json:"stateRoot"`
TxHash common.Hash `json:"transactionsRoot"`
ReceiptHash common.Hash `json:"receiptsRoot"`
Bloom types.Bloom `json:"logsBloom"`
Difficulty hexutil.Big `json:"difficulty"`
Number hexutil.Big `json:"number"`
GasLimit hexutil.Uint64 `json:"gasLimit"`
GasUsed hexutil.Uint64 `json:"gasUsed"`
Time hexutil.Big `json:"timestamp"`
Extra hexutil.Bytes `json:"extraData"`
Nonce types.BlockNonce `json:"nonce"`
GethHash common.Hash `json:"mixHash"`
ParityHash common.Hash `json:"hash"`
}
var emptyHash = common.Hash{}
// Hash will return GethHash if it exists otherwise it returns the ParityHash
func (h BlockHeader) Hash() common.Hash {
if h.GethHash != emptyHash {
return h.GethHash
}
return h.ParityHash
}
// ToHead converts a given BlockHeader to a Head instance.
func (h BlockHeader) ToHead() *Head {
return NewHead(h.Number.ToInt(), h.Hash())
}
// Head represents a BlockNumber, BlockHash.
type Head struct {
ID uint64 `gorm:"primary_key;auto_increment"`
Hash common.Hash `gorm:"not null"`
Number int64 `gorm:"index;not null"`
}
// NewHead returns a Head instance with a BlockNumber and BlockHash.
func NewHead(bigint *big.Int, hash common.Hash) *Head {
if bigint == nil {
return nil
}
return &Head{
Number: bigint.Int64(),
Hash: hash,
}
}
// String returns a string representation of this number.
func (l *Head) String() string {
return l.ToInt().String()
}
// ToInt return the height as a *big.Int. Also handles nil by returning nil.
func (l *Head) ToInt() *big.Int {
if l == nil {
return nil
}
return big.NewInt(l.Number)
}
// GreaterThan compares BlockNumbers and returns true if the reciever BlockNumber is greater than
// the supplied BlockNumber
func (l *Head) GreaterThan(r *Head) bool {
if l == nil {
return false
}
if l != nil && r == nil {
return true
}
return l.Number > r.Number
}
// NextInt returns the next BlockNumber as big.int, or nil if nil to represent latest.
func (l *Head) NextInt() *big.Int {
if l == nil {
return nil
}
return new(big.Int).Add(l.ToInt(), big.NewInt(1))
}
// EthSubscription should implement Err() <-chan error and Unsubscribe()
type EthSubscription interface {
Err() <-chan error
Unsubscribe()
}
// Key holds the private key metadata for a given address that is used to unlock
// said key when given a password.
type Key struct {
Address EIP55Address `gorm:"primary_key;type:varchar(64)"`
JSON JSON `gorm:"type:text"`
}
// NewKeyFromFile creates an instance in memory from a key file on disk.
func NewKeyFromFile(path string) (*Key, error) {
dat, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
js := gjson.ParseBytes(dat)
address, err := NewEIP55Address(common.HexToAddress(js.Get("address").String()).Hex())
if err != nil {
return nil, multierr.Append(errors.New("unable to create Key model"), err)
}
return &Key{
Address: address,
JSON: JSON{Result: js},
}, nil
}
// WriteToDisk writes this key to disk at the passed path.
func (k *Key) WriteToDisk(path string) error {
return ioutil.WriteFile(path, []byte(k.JSON.String()), 0700)
}
// TxReceipt holds the block number and the transaction hash of a signed
// transaction that has been written to the blockchain.
type TxReceipt struct {
BlockNumber *Big `json:"blockNumber"`
BlockHash common.Hash `json:"blockHash"`
Hash common.Hash `json:"transactionHash"`
Logs []Log `json:"logs"`
}
// Unconfirmed returns true if the transaction is not confirmed.
func (txr *TxReceipt) Unconfirmed() bool {
return txr.Hash == emptyHash || txr.BlockNumber == nil
}
func (txr TxReceipt) FulfilledRunLog() bool {
for _, log := range txr.Logs {
if log.Topics[0] == ChainlinkFulfilledTopic {
return true
}
}
return false
}