Skip to content
This repository has been archived by the owner on May 24, 2022. It is now read-only.

Commit

Permalink
[client/chains] wip
Browse files Browse the repository at this point in the history
  • Loading branch information
miguelmota committed Feb 12, 2019
1 parent f3d8715 commit 06c32e0
Show file tree
Hide file tree
Showing 22 changed files with 600 additions and 150 deletions.
61 changes: 45 additions & 16 deletions client/chain/chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ type Chain struct {
}

// NewChain ...
// TODO: configClient?
func NewChain(config *clienttypes.ConfigClient) (*Chain, error) {
var err error

Expand All @@ -48,9 +47,10 @@ func NewChain(config *clienttypes.ConfigClient) (*Chain, error) {
return nil, err
}

bestHash := c.Blocks.BestHash.Get()
bestNumber := c.Blocks.BestNumber.Get()
bestHash := c.Blocks.BestHash.Get(nil)
bestNumber := c.Blocks.BestNumber.Get(nil)
logGenesis := ""

if bestNumber.Cmp(big.NewInt(0)) != 0 {
logGenesis = fmt.Sprintf("(genesis %s)", u8util.ToHex(c.Genesis.Block.Hash[:], 48, true))
}
Expand All @@ -68,7 +68,7 @@ func NewChain(config *clienttypes.ConfigClient) (*Chain, error) {

// InitGenesis ...
func (c *Chain) InitGenesis() (*clientchaintypes.ChainGenesis, error) {
bestHash := c.Blocks.BestHash.Get()
bestHash := c.Blocks.BestHash.Get(nil)
if bestHash == nil || len(bestHash) == 0 {
return c.CreateGenesis()
}
Expand All @@ -86,12 +86,12 @@ func (c *Chain) InitGenesisFromBest(bestHeader *clienttypes.Header, rollback boo
logger.Error("[chain] state root is nil")
}
hexState := u8util.ToHex(bestHeader.StateRoot[:], 48, true)
fmt.Printf("Initializing from state %s", hexState)
fmt.Printf("[chain] initializing from state %s\n", hexState)

c.State.DB.SetRoot(bestHeader.StateRoot[:])

if u8util.ToHex(c.State.DB.GetRoot(), 48, true) != hexState {
log.Fatalf("Unable to move state to %s", hexState)
log.Fatalf("[chain] unable to move state to %s\n", hexState)
}

genesisHash := c.Blocks.Hash.Get(0)
Expand All @@ -115,38 +115,39 @@ func (c *Chain) RollbackBlock(bestHeader *clienttypes.Header, rollback bool) *cl
prevNumber := bestHeader.BlockNumber.Int64() - 1

if rollback && prevNumber > 1 {
fmt.Printf("Unable to validate root, moving to block #%d, %s\n", prevNumber, u8util.ToHex(prevHash, 48, true))
fmt.Printf("[chain] unable to validate root, moving to block #%d, %s\n", prevNumber, u8util.ToHex(prevHash, 48, true))

prevBlock := c.GetBlock(prevHash)

c.Blocks.BestHash.Set(prevHash)
c.Blocks.BestHash.Set(prevHash, nil)
c.Blocks.BestNumber.Set(prevBlock.Header.BlockNumber)

return c.InitGenesisFromBest(prevBlock.Header, false)
}

panic("Unable to retrieve genesis hash, aborting")
log.Fatal("[chain] unable to retrieve genesis hash. aborting\n")
return nil
}

// GetBlock ...
func (c *Chain) GetBlock(headerHash []uint8) *clienttypes.BlockData {
data := c.Blocks.BlockData.Get(headerHash)

if data == nil || len(data) == 0 {
log.Fatalf("Unable to retrieve block %s\n", u8util.ToHex(headerHash, -1, true))
log.Fatalf("[chain] unable to retrieve block %s\n", u8util.ToHex(headerHash, -1, true))
}

return clienttypes.NewBlockData(data)
}

// GetCode ...
func (c *Chain) GetCode() []uint8 {
_, decodedValue := u8compact.StripLength(storagetypes.Substrate.Code(), 32)
_, decodedValue := u8compact.StripLength(storagetypes.Substrate.Code(nil), -1)

code := c.State.DB.Get(decodedValue)

if code == nil || len(code) == 0 {
panic("Unable to retrieve genesis code")
log.Fatal("[chain] unable to retrieve genesis code")
}

return code
Expand All @@ -161,7 +162,7 @@ func (c *Chain) CreateGenesis() (*clientchaintypes.ChainGenesis, error) {
return nil, err
}

c.Blocks.BestHash.Set(genesis.Block.Hash[:])
c.Blocks.BestHash.Set(genesis.Block.Hash[:], nil)
c.Blocks.BestNumber.Set(big.NewInt(0))
c.Blocks.BlockData.Set(genesis.Block.ToU8a(), genesis.Block.Hash)
c.Blocks.Hash.Set(genesis.Block.Hash[:], 0)
Expand All @@ -175,9 +176,9 @@ func (c *Chain) CreateGenesisBlock() (*clientchaintypes.ChainGenesis, error) {
if err != nil {
return nil, err
}
header.SetStateRoot(crypto.NewBlake2b256(c.State.DB.GetRoot()))
header.SetExtrinsicsRoot(crypto.NewBlake2b256(triehash.TrieRoot(nil)))
header.SetParentHash(crypto.NewBlake2b256(make([]uint8, 32)))
header.SetStateRoot(crypto.NewBlake2b256(c.State.DB.GetRoot())[:])
header.SetExtrinsicsRoot(crypto.NewBlake2b256(triehash.TrieRoot(nil))[:])
header.SetParentHash(crypto.NewBlake2b256(make([]uint8, 32))[:])

block := clienttypes.NewBlockData(map[string]interface{}{
"hash": header.Hash,
Expand Down Expand Up @@ -214,3 +215,31 @@ func (c *Chain) CreateGenesisState() {
logger.Errorf("[chain] statedb ok: %v, err:\n%v", ok, err)
}
}

// GetBestBlocksHash ...
func (c *Chain) GetBestBlocksHash() ([]byte, error) {
return c.Blocks.BestHash.Get(nil), nil
}

// GetBestBlocksNumber ...
func (c *Chain) GetBestBlocksNumber() (*big.Int, error) {
return c.Blocks.BestNumber.Get(), nil
}

// GetBlockDataByHash ...
func (c *Chain) GetBlockDataByHash(hash []byte) (*clienttypes.StateBlock, error) {
// TODO
return nil, nil
}

// GetGenesisHash ...
func (c *Chain) GetGenesisHash() ([]byte, error) {
// TODO
return nil, nil
}

// ImportBlock ...
func (c *Chain) ImportBlock(block *clienttypes.StateBlock) (bool, error) {
// TODO
return false, nil
}
37 changes: 22 additions & 15 deletions client/client.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
package client

import (
"context"
"fmt"
"log"
"math/big"
"time"

clientchain "github.com/opennetsys/golkadot/client/chain"
p2p "github.com/opennetsys/golkadot/client/p2p"
clienttypes "github.com/opennetsys/golkadot/client/types"
)

// TODO: https://github.com/polkadot-js/client/blob/master/packages/client/src/index.ts

// TODO: these are placeholders. need to implement in their respective package

// InformantDelay ...
var InformantDelay = 10000

Expand All @@ -36,16 +38,21 @@ func NewClient() *Client {
// Start ...
func (c *Client) Start(config *clienttypes.ConfigClient) {
// TODO: implement
/*
c.chain = clientchain.NewChain(config)
c.p2p = NewP2P(config, c.chain)
c.rpc = NewRPC(config, c.chain)
c.telemetry = NewTelemetry(config, c.chain)
c.p2p.Start()
c.rpc.Start()
c.telemetry.Start()
*/
var err error
c.Chain, err = clientchain.NewChain(config)
if err != nil {
log.Fatal(err)
}
c.P2P, err = p2p.New(context.Background(), nil, nil, config, c.Chain)
if err != nil {
log.Fatal(err)
}
//c.RPC = NewRPC(config, c.Chain)
//c.Telemetry = NewTelemetry(config, c.Chain)

c.P2P.Start()
//c.RPC.Start()
//c.Telemetry.Start()

c.StartInformant()
}
Expand All @@ -58,15 +65,15 @@ func (c *Client) Stop() {
// StartInformant ...
func (c *Client) StartInformant() {
// TODO: implement
//c.informantID = setInterval(c.runInformant, InformationDelay)
//c.InformantID = setInterval(c.RunInformant, InformationDelay)

if c.P2P == nil {
return
}

// TODO: implement
/*
c.p2p.sync.on("imported", func () {
c.P2P.Sync.on("imported", func () {
if c.telemetry != nil {
c.telemetry.BlockImported()
}
Expand Down Expand Up @@ -129,7 +136,7 @@ func (c *Client) RunInformant() {

if c.Telemetry != nil {
// TODO: implement
// c.telemetry.intervalInfo(numPeers, status)
// c.Telemetry.intervalInfo(numPeers, status)
}
}

Expand Down
3 changes: 1 addition & 2 deletions client/db/block.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ import (
)

func createU8a(dbs db.BaseDB, fn types.StorageFunction) StorageMethodU8a {
// TODO
return StorageMethodU8a{}
return NewStorageMethodU8a(dbs, fn)
}

func createBn(dbs db.BaseDB, fn types.StorageFunction, n int) StorageMethodBn {
Expand Down
69 changes: 61 additions & 8 deletions client/db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"github.com/opennetsys/golkadot/common/db"
diskdb "github.com/opennetsys/golkadot/common/diskdb"
"github.com/opennetsys/golkadot/common/triedb"
types "github.com/opennetsys/golkadot/types"
)

// TODO: https://github.com/polkadot-js/client/blob/master/packages/client-db/src/index.ts
Expand Down Expand Up @@ -45,31 +46,40 @@ type InterfaceChainDbs interface {
// StorageMethodU8a ...
// TODO
type StorageMethodU8a struct {
base *Base
createKey types.StorageFunction
//Del(params ...interface{})
//Get(params ...interface{}) []uint8
//Set(value []uint8, params ...interface{})
//OnUpdate(callback func(value []uint8))
}

// NewStorageMethodU8a ...
func NewStorageMethodU8a(dbs db.BaseDB, createKey types.StorageFunction) StorageMethodU8a {
return StorageMethodU8a{
base: NewBase(dbs),
createKey: createKey,
}
}

// Del ...
func (s *StorageMethodU8a) Del(params ...interface{}) {
// TODO
func (s *StorageMethodU8a) Del(keyParam interface{}) {
s.base.Del(s.createKey(keyParam))
}

// Get ...
func (s *StorageMethodU8a) Get(params ...interface{}) []uint8 {
// TODO
return nil
func (s *StorageMethodU8a) Get(keyParam interface{}) []uint8 {
return s.base.Get(s.createKey(keyParam))
}

// Set ...
func (s *StorageMethodU8a) Set(value []uint8, params ...interface{}) {
// TODO
func (s *StorageMethodU8a) Set(value []uint8, keyParam interface{}) {
s.base.Set(s.createKey(keyParam), value)
}

// OnUpdate ...
func (s *StorageMethodU8a) OnUpdate(callback func(value []uint8)) {
// TODO
s.base.OnUpdate(callback)
}

// StorageMethodBn ...
Expand Down Expand Up @@ -112,6 +122,10 @@ func NewDB(config *clienttypes.ConfigClient, chain *clientchainloader.Loader) *D
log.Fatal("config must not be nil")
}

if config.DB == nil {
log.Fatal("config db must not be nil")
}

ret := &DB{}
ret.Config = config.DB

Expand Down Expand Up @@ -216,3 +230,42 @@ func (c *DB) Blocks() *BlockDB {
func (c *DB) State() *StateDB {
return c.StateDB
}

// Base ...
type Base struct {
db db.BaseDB
}

// NewBase ...
func NewBase(dbs db.BaseDB) *Base {
return &Base{
db: dbs,
}
}

// Del ...
func (b *Base) Del(key []uint8) {
b.db.Del(key)
}

// Get ...
func (b *Base) Get(key []uint8) []uint8 {
value := b.db.Get(key)

return value
}

// Set ...
func (b *Base) Set(key []uint8, value []uint8) []uint8 {
b.db.Put(key, value)
// b.subscribers.each(func(subscriber) {
// subscriber(value)
//})

return value
}

// OnUpdate ...
func (b *Base) OnUpdate(subscriber func(value []uint8)) {
// b.subscribers = append(b.subscribers, subscriber)
}
2 changes: 2 additions & 0 deletions client/db/db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,6 @@ func TestClientDB(t *testing.T) {
},
}, &clientchainloader.Loader{})
_ = db

// TODO
}
6 changes: 3 additions & 3 deletions client/p2p/defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,16 @@ var DefaultClientID = "golkadot/0.0.0"
var DefaultAddress = "127.0.0.1"

// DefaultMaxPeers ...
var DefaultMaxPeers = 25
var DefaultMaxPeers uint = 25

// DefaultPort ...
var DefaultPort = 31333
var DefaultPort uint = 31333

// DefaultProtocolPing ...
var DefaultProtocolPing = "/ipfs/ping/1.0.0"

// DefaultMaxRequestBlocks ...
var DefaultMaxRequestBlocks = 64
var DefaultMaxRequestBlocks uint = 64

// DefaultProtocolBase ...
// TODO: change...
Expand Down
2 changes: 1 addition & 1 deletion client/p2p/p2p.go
Original file line number Diff line number Diff line change
Expand Up @@ -769,6 +769,6 @@ func (p *P2P) handleEvent(event p2ptypes.EventEnum) {
}

//// TODO ...
//func (p *P2P) announceBlock(hash *crypto.Blake2b256Hash, header []byte, body []byte) {
//func (p *P2P) announceBlock(hash []byte, header []byte, body []byte) {
//return
//}
Loading

0 comments on commit 06c32e0

Please sign in to comment.