aboutsummaryrefslogtreecommitdiffstats
path: root/ethchain/block.go
blob: e00bcb24f88cbbfe76f4e08cc26751640972a572 (plain) (blame)
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
package ethchain

import (
    "bytes"
    "fmt"
    "math/big"
    _ "strconv"
    "time"

    "github.com/ethereum/eth-go/ethcrypto"
    "github.com/ethereum/eth-go/ethstate"
    "github.com/ethereum/eth-go/ethtrie"
    "github.com/ethereum/eth-go/ethutil"
)

type BlockInfo struct {
    Number uint64
    Hash   []byte
    Parent []byte
}

func (bi *BlockInfo) RlpDecode(data []byte) {
    decoder := ethutil.NewValueFromBytes(data)

    bi.Number = decoder.Get(0).Uint()
    bi.Hash = decoder.Get(1).Bytes()
    bi.Parent = decoder.Get(2).Bytes()
}

func (bi *BlockInfo) RlpEncode() []byte {
    return ethutil.Encode([]interface{}{bi.Number, bi.Hash, bi.Parent})
}

type Block struct {
    // Hash to the previous block
    PrevHash []byte
    // Uncles of this block
    Uncles   []*Block
    UncleSha []byte
    // The coin base address
    Coinbase []byte
    // Block Trie state
    //state *ethutil.Trie
    state *ethstate.State
    // Difficulty for the current block
    Difficulty *big.Int
    // Creation time
    Time int64
    // The block number
    Number *big.Int
    // Minimum Gas Price
    MinGasPrice *big.Int
    // Gas limit
    GasLimit *big.Int
    // Gas used
    GasUsed *big.Int
    // Extra data
    Extra string
    // Block Nonce for verification
    Nonce []byte
    // List of transactions and/or contracts
    transactions []*Transaction
    receipts     []*Receipt
    TxSha        []byte
}

func NewBlockFromBytes(raw []byte) *Block {
    block := &Block{}
    block.RlpDecode(raw)

    return block
}

// New block takes a raw encoded string
func NewBlockFromRlpValue(rlpValue *ethutil.Value) *Block {
    block := &Block{}
    block.RlpValueDecode(rlpValue)

    return block
}

func CreateBlock(root interface{},
    prevHash []byte,
    base []byte,
    Difficulty *big.Int,
    Nonce []byte,
    extra string) *Block {

    block := &Block{
        PrevHash:    prevHash,
        Coinbase:    base,
        Difficulty:  Difficulty,
        Nonce:       Nonce,
        Time:        time.Now().Unix(),
        Extra:       extra,
        UncleSha:    EmptyShaList,
        GasUsed:     new(big.Int),
        MinGasPrice: new(big.Int),
        GasLimit:    new(big.Int),
    }
    block.SetUncles([]*Block{})

    block.state = ethstate.NewState(ethtrie.NewTrie(ethutil.Config.Db, root))

    return block
}

// Returns a hash of the block
func (block *Block) Hash() []byte {
    return ethcrypto.Sha3Bin(block.Value().Encode())
}

func (block *Block) HashNoNonce() []byte {
    return ethcrypto.Sha3Bin(ethutil.Encode([]interface{}{block.PrevHash,
        block.UncleSha, block.Coinbase, block.state.Trie.Root,
        block.TxSha, block.Difficulty, block.Number, block.MinGasPrice,
        block.GasLimit, block.GasUsed, block.Time, block.Extra}))
}

func (block *Block) State() *ethstate.State {
    return block.state
}

func (block *Block) Transactions() []*Transaction {
    return block.transactions
}

func (block *Block) PayFee(addr []byte, fee *big.Int) bool {
    contract := block.state.GetStateObject(addr)
    // If we can't pay the fee return
    if contract == nil || contract.Amount.Cmp(fee) < 0 /* amount < fee */ {
        fmt.Println("Contract has insufficient funds", contract.Amount, fee)

        return false
    }

    base := new(big.Int)
    contract.Amount = base.Sub(contract.Amount, fee)
    block.state.Trie.Update(string(addr), string(contract.RlpEncode()))

    data := block.state.Trie.Get(string(block.Coinbase))

    // Get the ether (Coinbase) and add the fee (gief fee to miner)
    account := ethstate.NewStateObjectFromBytes(block.Coinbase, []byte(data))

    base = new(big.Int)
    account.Amount = base.Add(account.Amount, fee)

    //block.state.Trie.Update(string(block.Coinbase), string(ether.RlpEncode()))
    block.state.UpdateStateObject(account)

    return true
}

func (block *Block) CalcGasLimit(parent *Block) *big.Int {
    if block.Number.Cmp(big.NewInt(0)) == 0 {
        return ethutil.BigPow(10, 6)
    }

    previous := new(big.Int).Mul(big.NewInt(1023), parent.GasLimit)
    current := new(big.Rat).Mul(new(big.Rat).SetInt(block.GasUsed), big.NewRat(6, 5))
    curInt := new(big.Int).Div(current.Num(), current.Denom())

    result := new(big.Int).Add(previous, curInt)
    result.Div(result, big.NewInt(1024))

    min := big.NewInt(125000)

    return ethutil.BigMax(min, result)
    /*
        base := new(big.Int)
        base2 := new(big.Int)
        parentGL := bc.CurrentBlock.GasLimit
        parentUsed := bc.CurrentBlock.GasUsed

        base.Mul(parentGL, big.NewInt(1024-1))
        base2.Mul(parentUsed, big.NewInt(6))
        base2.Div(base2, big.NewInt(5))
        base.Add(base, base2)
        base.Div(base, big.NewInt(1024))
    */

}

func (block *Block) BlockInfo() BlockInfo {
    bi := BlockInfo{}
    data, _ := ethutil.Config.Db.Get(append(block.Hash(), []byte("Info")...))
    bi.RlpDecode(data)

    return bi
}

func (self *Block) GetTransaction(hash []byte) *Transaction {
    for _, receipt := range self.receipts {
        if bytes.Compare(receipt.Tx.Hash(), hash) == 0 {
            return receipt.Tx
        }
    }

    return nil
}

// Sync the block's state and contract respectively
func (block *Block) Sync() {
    block.state.Sync()
}

func (block *Block) Undo() {
    // Sync the block state itself
    block.state.Reset()
}

/////// Block Encoding
func (block *Block) rlpReceipts() interface{} {
    // Marshal the transactions of this block
    encR := make([]interface{}, len(block.receipts))
    for i, r := range block.receipts {
        // Cast it to a string (safe)
        encR[i] = r.RlpData()
    }

    return encR
}

func (block *Block) rlpUncles() interface{} {
    // Marshal the transactions of this block
    uncles := make([]interface{}, len(block.Uncles))
    for i, uncle := range block.Uncles {
        // Cast it to a string (safe)
        uncles[i] = uncle.header()
    }

    return uncles
}

func (block *Block) SetUncles(uncles []*Block) {
    block.Uncles = uncles

    // Sha of the concatenated uncles
    block.UncleSha = ethcrypto.Sha3Bin(ethutil.Encode(block.rlpUncles()))
}

func (self *Block) SetReceipts(receipts []*Receipt, txs []*Transaction) {
    self.receipts = receipts
    self.setTransactions(txs)
}

func (block *Block) setTransactions(txs []*Transaction) {
    block.transactions = txs

    /*
        trie := ethtrie.NewTrie(ethutil.Config.Db, "")
        for i, tx := range txs {
            trie.Update(strconv.Itoa(i), string(tx.RlpEncode()))
        }

        switch trie.Root.(type) {
        case string:
            block.TxSha = []byte(trie.Root.(string))
        case []byte:
            block.TxSha = trie.Root.([]byte)
        default:
            panic(fmt.Sprintf("invalid root type %T", trie.Root))
        }
    */
}

func CreateTxSha(receipts Receipts) (sha []byte) {
    trie := ethtrie.NewTrie(ethutil.Config.Db, "")
    for i, receipt := range receipts {
        trie.Update(string(ethutil.NewValue(i).Encode()), string(ethutil.NewValue(receipt.RlpData()).Encode()))
    }

    switch trie.Root.(type) {
    case string:
        sha = []byte(trie.Root.(string))
    case []byte:
        sha = trie.Root.([]byte)
    default:
        panic(fmt.Sprintf("invalid root type %T", trie.Root))
    }

    return sha
}

func (self *Block) SetTxHash(receipts Receipts) {
    self.TxSha = CreateTxSha(receipts)
}

func (block *Block) Value() *ethutil.Value {
    return ethutil.NewValue([]interface{}{block.header(), block.rlpReceipts(), block.rlpUncles()})
}

func (block *Block) RlpEncode() []byte {
    // Encode a slice interface which contains the header and the list of
    // transactions.
    return block.Value().Encode()
}

func (block *Block) RlpDecode(data []byte) {
    rlpValue := ethutil.NewValueFromBytes(data)
    block.RlpValueDecode(rlpValue)
}

func (block *Block) RlpValueDecode(decoder *ethutil.Value) {
    header := decoder.Get(0)

    block.PrevHash = header.Get(0).Bytes()
    block.UncleSha = header.Get(1).Bytes()
    block.Coinbase = header.Get(2).Bytes()
    block.state = ethstate.NewState(ethtrie.NewTrie(ethutil.Config.Db, header.Get(3).Val))
    block.TxSha = header.Get(4).Bytes()
    block.Difficulty = header.Get(5).BigInt()
    block.Number = header.Get(6).BigInt()
    //fmt.Printf("#%v : %x\n", block.Number, block.Coinbase)
    block.MinGasPrice = header.Get(7).BigInt()
    block.GasLimit = header.Get(8).BigInt()
    block.GasUsed = header.Get(9).BigInt()
    block.Time = int64(header.Get(10).BigInt().Uint64())
    block.Extra = header.Get(11).Str()
    block.Nonce = header.Get(12).Bytes()

    // Tx list might be empty if this is an uncle. Uncles only have their
    // header set.
    if decoder.Get(1).IsNil() == false { // Yes explicitness
        receipts := decoder.Get(1)
        block.transactions = make([]*Transaction, receipts.Len())
        block.receipts = make([]*Receipt, receipts.Len())
        for i := 0; i < receipts.Len(); i++ {
            receipt := NewRecieptFromValue(receipts.Get(i))
            block.transactions[i] = receipt.Tx
            block.receipts[i] = receipt
        }

    }

    if decoder.Get(2).IsNil() == false { // Yes explicitness
        uncles := decoder.Get(2)
        block.Uncles = make([]*Block, uncles.Len())
        for i := 0; i < uncles.Len(); i++ {
            block.Uncles[i] = NewUncleBlockFromValue(uncles.Get(i))
        }
    }

}

func NewUncleBlockFromValue(header *ethutil.Value) *Block {
    block := &Block{}

    block.PrevHash = header.Get(0).Bytes()
    block.UncleSha = header.Get(1).Bytes()
    block.Coinbase = header.Get(2).Bytes()
    block.state = ethstate.NewState(ethtrie.NewTrie(ethutil.Config.Db, header.Get(3).Val))
    block.TxSha = header.Get(4).Bytes()
    block.Difficulty = header.Get(5).BigInt()
    block.Number = header.Get(6).BigInt()
    block.MinGasPrice = header.Get(7).BigInt()
    block.GasLimit = header.Get(8).BigInt()
    block.GasUsed = header.Get(9).BigInt()
    block.Time = int64(header.Get(10).BigInt().Uint64())
    block.Extra = header.Get(11).Str()
    block.Nonce = header.Get(12).Bytes()

    return block
}

func (block *Block) GetRoot() interface{} {
    return block.state.Trie.Root
}

func (self *Block) Receipts() []*Receipt {
    return self.receipts
}

func (block *Block) header() []interface{} {
    return []interface{}{
        // Sha of the previous block
        block.PrevHash,
        // Sha of uncles
        block.UncleSha,
        // Coinbase address
        block.Coinbase,
        // root state
        block.state.Trie.Root,
        // Sha of tx
        block.TxSha,
        // Current block Difficulty
        block.Difficulty,
        // The block number
        block.Number,
        // Block minimum gas price
        block.MinGasPrice,
        // Block upper gas bound
        block.GasLimit,
        // Block gas used
        block.GasUsed,
        // Time the block was found?
        block.Time,
        // Extra data
        block.Extra,
        // Block's Nonce for validation
        block.Nonce,
    }
}

func (block *Block) String() string {
    return fmt.Sprintf(`
    BLOCK(%x):
    PrevHash:   %x
    UncleSha:   %x
    Coinbase:   %x
    Root:       %x
    TxSha:      %x
    Difficulty: %v
    Number:     %v
    MinGas:     %v
    MaxLimit:   %v
    GasUsed:    %v
    Time:       %v
    Extra:      %v
    Nonce:      %x
    NumTx:      %v
`,
        block.Hash(),
        block.PrevHash,
        block.UncleSha,
        block.Coinbase,
        block.state.Trie.Root,
        block.TxSha,
        block.Difficulty,
        block.Number,
        block.MinGasPrice,
        block.GasLimit,
        block.GasUsed,
        block.Time,
        block.Extra,
        block.Nonce,
        len(block.transactions),
    )
}