OSDN Git Service

cb7111d59b7a5450c3b678a6d3a2b07b9dcaf9f2
[bytom/bytom.git] / protocol / state / contract_view.go
1 package state
2
3 import (
4         "github.com/bytom/bytom/consensus/bcrp"
5         "github.com/bytom/bytom/crypto/sha3pool"
6         "github.com/bytom/bytom/protocol/bc/types"
7 )
8
9 // ContractViewpoint represents a view into the set of registered contract
10 type ContractViewpoint struct {
11         AttachEntries map[[32]byte][]byte
12         DetachEntries map[[32]byte][]byte
13 }
14
15 // NewContractViewpoint returns a new empty contract view.
16 func NewContractViewpoint() *ContractViewpoint {
17         return &ContractViewpoint{
18                 AttachEntries: make(map[[32]byte][]byte),
19                 DetachEntries: make(map[[32]byte][]byte),
20         }
21 }
22
23 // ApplyBlock apply block contract to contract view
24 func (view *ContractViewpoint) ApplyBlock(block *types.Block) error {
25         for _, tx := range block.Transactions {
26                 for _, output := range tx.Outputs {
27                         program := output.ControlProgram
28                         if !bcrp.IsBCRPScript(program) {
29                                 continue
30                         }
31                         var hash [32]byte
32                         sha3pool.Sum256(hash[:], program)
33                         view.AttachEntries[hash] = append(tx.ID.Bytes(), program...)
34                 }
35         }
36         return nil
37 }
38
39 // DetachBlock detach block contract to contract view
40 func (view *ContractViewpoint) DetachBlock(block *types.Block) error {
41         for _, tx := range block.Transactions {
42                 for _, output := range tx.Outputs {
43                         program := output.ControlProgram
44                         if !bcrp.IsBCRPScript(program) {
45                                 continue
46                         }
47                         var hash [32]byte
48                         sha3pool.Sum256(hash[:], program)
49                         view.DetachEntries[hash] = append(tx.ID.Bytes(), program...)
50                 }
51         }
52         return nil
53 }