aboutsummaryrefslogtreecommitdiff
path: root/plugin/evm/block.go
blob: 9c15834ee63b8d559ea201bae3b757e64aab6b95 (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
// (c) 2019-2020, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.

package evm

import (
	"fmt"

	"github.com/ava-labs/coreth/core/types"
	"github.com/ava-labs/go-ethereum/rlp"

	"github.com/ava-labs/gecko/ids"
	"github.com/ava-labs/gecko/snow/choices"
	"github.com/ava-labs/gecko/snow/consensus/snowman"
)

// Block implements the snowman.Block interface
type Block struct {
	id       ids.ID
	ethBlock *types.Block
	vm       *VM
}

// ID implements the snowman.Block interface
func (b *Block) ID() ids.ID { return b.id }

// Accept implements the snowman.Block interface
func (b *Block) Accept() error {
	b.vm.ctx.Log.Verbo("Block %s is accepted", b.ID())
	b.vm.updateStatus(b.ID(), choices.Accepted)
	return nil
}

// Reject implements the snowman.Block interface
func (b *Block) Reject() error {
	b.vm.ctx.Log.Verbo("Block %s is rejected", b.ID())
	b.vm.updateStatus(b.ID(), choices.Rejected)
	return nil
}

// Status implements the snowman.Block interface
func (b *Block) Status() choices.Status {
	status := b.vm.getCachedStatus(b.ID())
	if status == choices.Unknown && b.ethBlock != nil {
		return choices.Processing
	}
	return status
}

// Parent implements the snowman.Block interface
func (b *Block) Parent() snowman.Block {
	parentID := ids.NewID(b.ethBlock.ParentHash())
	block := &Block{
		id:       parentID,
		ethBlock: b.vm.getCachedBlock(parentID),
		vm:       b.vm,
	}
	b.vm.ctx.Log.Verbo("Parent(%s) has status: %s", block.ID(), block.Status())
	return block
}

// Verify implements the snowman.Block interface
func (b *Block) Verify() error {
	p := b
	path := []*Block{}
	for {
		if p.Status() == choices.Accepted {
			break
		}
		path = append(path, p)
		p = p.Parent().(*Block)
	}
	inputs := new(ids.Set)
	for i := len(path) - 1; i >= 0; i-- {
		p := path[i]
		atx := p.vm.getAtomicTx(p.ethBlock)
		inputs.Union(atx.UnsignedTx.(UnsignedAtomicTx).InputUTXOs())
	}
	tx := b.vm.getAtomicTx(b.ethBlock)
	atx := tx.UnsignedTx.(*UnsignedImportTx)
	if atx.SemanticVerify(b.vm, tx) != nil {
		return errInvalidBlock
	}

	_, err := b.vm.chain.InsertChain([]*types.Block{b.ethBlock})
	return err
}

// Bytes implements the snowman.Block interface
func (b *Block) Bytes() []byte {
	res, err := rlp.EncodeToBytes(b.ethBlock)
	if err != nil {
		panic(err)
	}
	return res
}

func (b *Block) String() string { return fmt.Sprintf("EVM block, ID = %s", b.ID()) }