go-ethereum/ethchain/contract.go

73 lines
1.7 KiB
Go
Raw Normal View History

2014-02-14 16:56:09 -06:00
package ethchain
import (
"github.com/ethereum/eth-go/ethutil"
"math/big"
)
type Contract struct {
Amount *big.Int
Nonce uint64
//state *ethutil.Trie
state *State
2014-02-14 16:56:09 -06:00
}
func NewContract(Amount *big.Int, root []byte) *Contract {
contract := &Contract{Amount: Amount, Nonce: 0}
contract.state = NewState(ethutil.NewTrie(ethutil.Config.Db, string(root)))
2014-02-14 16:56:09 -06:00
return contract
}
func (c *Contract) RlpEncode() []byte {
return ethutil.Encode([]interface{}{c.Amount, c.Nonce, c.state.trie.Root})
2014-02-14 16:56:09 -06:00
}
func (c *Contract) RlpDecode(data []byte) {
2014-02-14 18:34:18 -06:00
decoder := ethutil.NewValueFromBytes(data)
2014-02-14 16:56:09 -06:00
2014-02-14 18:34:18 -06:00
c.Amount = decoder.Get(0).BigInt()
c.Nonce = decoder.Get(1).Uint()
c.state = NewState(ethutil.NewTrie(ethutil.Config.Db, decoder.Get(2).Interface()))
2014-02-14 16:56:09 -06:00
}
2014-02-20 16:10:36 -06:00
func (c *Contract) Addr(addr []byte) *ethutil.Value {
return ethutil.NewValueFromBytes([]byte(c.state.trie.Get(string(addr))))
2014-02-20 16:10:36 -06:00
}
func (c *Contract) SetAddr(addr []byte, value interface{}) {
c.state.trie.Update(string(addr), string(ethutil.NewValue(value).Encode()))
2014-02-20 16:10:36 -06:00
}
func (c *Contract) State() *State {
2014-02-14 16:56:09 -06:00
return c.state
}
2014-02-24 05:12:24 -06:00
func (c *Contract) GetMem(num int) *ethutil.Value {
nb := ethutil.BigToBytes(big.NewInt(int64(num)), 256)
return c.Addr(nb)
}
func MakeContract(tx *Transaction, state *State) *Contract {
// Create contract if there's no recipient
if tx.IsContract() {
addr := tx.Hash()[12:]
value := tx.Value
contract := NewContract(value, []byte(""))
state.trie.Update(string(addr), string(contract.RlpEncode()))
for i, val := range tx.Data {
if len(val) > 0 {
bytNum := ethutil.BigToBytes(big.NewInt(int64(i)), 256)
contract.state.trie.Update(string(bytNum), string(ethutil.Encode(val)))
2014-02-24 05:12:24 -06:00
}
}
state.trie.Update(string(addr), string(contract.RlpEncode()))
return contract
}
return nil
}