github.com/iotexproject/iotex-core@v1.14.1-rc1/action/protocol/managers.go (about) 1 package protocol 2 3 import ( 4 "github.com/iotexproject/go-pkgs/hash" 5 "github.com/pkg/errors" 6 7 "github.com/iotexproject/iotex-core/state" 8 ) 9 10 // NamespaceOption creates an option for given namesapce 11 func NamespaceOption(ns string) StateOption { 12 return func(sc *StateConfig) error { 13 sc.Namespace = ns 14 return nil 15 } 16 } 17 18 // KeyOption sets the key for call 19 func KeyOption(key []byte) StateOption { 20 return func(cfg *StateConfig) error { 21 cfg.Key = make([]byte, len(key)) 22 copy(cfg.Key, key) 23 return nil 24 } 25 } 26 27 // KeysOption sets the key for call 28 func KeysOption(f func() ([][]byte, error)) StateOption { 29 return func(cfg *StateConfig) (err error) { 30 cfg.Keys, err = f() 31 return err 32 } 33 } 34 35 // LegacyKeyOption sets the key for call with legacy key 36 func LegacyKeyOption(key hash.Hash160) StateOption { 37 return func(cfg *StateConfig) error { 38 cfg.Key = make([]byte, len(key[:])) 39 copy(cfg.Key, key[:]) 40 return nil 41 } 42 } 43 44 // CreateStateConfig creates a config for accessing stateDB 45 func CreateStateConfig(opts ...StateOption) (*StateConfig, error) { 46 cfg := StateConfig{} 47 for _, opt := range opts { 48 if err := opt(&cfg); err != nil { 49 return nil, errors.Wrap(err, "failed to execute state option") 50 } 51 } 52 return &cfg, nil 53 } 54 55 type ( 56 // StateConfig is the config for accessing stateDB 57 StateConfig struct { 58 Namespace string // namespace used by state's storage 59 Key []byte 60 Keys [][]byte 61 } 62 63 // StateOption sets parameter for access state 64 StateOption func(*StateConfig) error 65 66 // StateReader defines an interface to read stateDB 67 StateReader interface { 68 Height() (uint64, error) 69 State(interface{}, ...StateOption) (uint64, error) 70 States(...StateOption) (uint64, state.Iterator, error) 71 ReadView(string) (interface{}, error) 72 } 73 74 // StateManager defines the stateDB interface atop IoTeX blockchain 75 StateManager interface { 76 StateReader 77 // Accounts 78 Snapshot() int 79 Revert(int) error 80 // General state 81 PutState(interface{}, ...StateOption) (uint64, error) 82 DelState(...StateOption) (uint64, error) 83 WriteView(string, interface{}) error 84 Dock 85 } 86 87 // Dock defines an interface for protocol to read/write their private data in StateReader/Manager 88 // data are stored as interface{}, user needs to type-assert on their own upon Unload() 89 Dock interface { 90 ProtocolDirty(string) bool 91 Load(string, string, interface{}) error 92 Unload(string, string, interface{}) error 93 Reset() 94 } 95 )