Skip to content

Commit

Permalink
Merge pull request DNAProject#136 from zhouziyan/master
Browse files Browse the repository at this point in the history
miner node join consensus networking automatically
  • Loading branch information
dreamfly281 authored Mar 24, 2017
2 parents 14558f2 + 0405d87 commit fe5a0ac
Show file tree
Hide file tree
Showing 20 changed files with 336 additions and 324 deletions.
5 changes: 1 addition & 4 deletions common/serialization/serialize.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,10 +166,7 @@ func WriteVarBytes(writer io.Writer, value []byte) error {
return err
}
_, err = writer.Write(value)
if err != nil {
return err
}
return nil
return err
}

func WriteVarString(writer io.Writer, value string) error {
Expand Down
2 changes: 0 additions & 2 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,11 @@ const (
type ProtocolConfiguration struct {
Magic int64 `json:"Magic"`
CoinVersion int `json:"CoinVersion"`
StandbyMiners []string `json:"StandbyMiners"`
SeedList []string `json:"SeedList"`
HttpJsonPort int `json:"HttpJsonPort"`
HttpLocalPort int `json:"HttpLocalPort"`
NodePort int `json:"NodePort"`
WebSocketPort int `json:"WebSocketPort"`
MinerName string `json:"MinerName"`
PrintLevel int `json:"PrintLevel"`
IsTLS bool `json:"IsTLS"`
CertPath string `json:"CertPath"`
Expand Down
10 changes: 0 additions & 10 deletions config/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,12 @@
"ProtocolConfiguration": {
"Magic": 7630401,
"CoinVersion": 23,
"StandbyMiners": [
"03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c",
"02df48f60e8f3e01c48ff40b9b7f1310d7a8b2a193188befe1c2e3df740e895093",
"03b8d9d5771d8f513aa0869b9cc8d50986403b78c6da36890638c3d46a5adce04a",
"02ca0e27697b9c248f6f16e085fd0061e26f44da85b58ee835c110caa5ec3ba554",
"024c7b7fb6c310fccf1ba33b082519d82964ea93868d676662d4a59ad548df0e7d",
"02aaec38470f6aad0042c6e877cfd8087d2676b0f516fddd362801b9bd3936399e",
"02486fd15702c4490a26703112a5cc1d0923fd697a33406bd5a1c00e0013b09a70"
],
"SeedList": [
"192.168.33.11:20338"
],
"HttpJsonPort": 20336,
"HttpLocalPort": 20337,
"NodePort": 20338,
"MinerName": "c1",
"PrintLevel": 0,
"IsTLS": false,
"CertPath": "./sample-cert.pem",
Expand Down
22 changes: 17 additions & 5 deletions consensus/dbft/consensusContext.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ import (
"GoOnchain/core/ledger"
tx "GoOnchain/core/transaction"
"GoOnchain/crypto"
"GoOnchain/net"
msg "GoOnchain/net/message"
"fmt"
"sort"
"sync"
)

Expand All @@ -21,6 +23,7 @@ type ConsensusContext struct {
Height uint32
ViewNumber byte
Miners []*crypto.PubKey
Owner *crypto.PubKey
MinerIndex int
PrimaryIndex uint32
Timestamp uint32
Expand Down Expand Up @@ -120,6 +123,7 @@ func (cxt *ConsensusContext) MakePayload(message ConsensusMessage) *msg.Consensu
MinerIndex: uint16(cxt.MinerIndex),
Timestamp: cxt.Timestamp,
Data: ser.ToArray(message),
Owner: cxt.Owner,
}
}

Expand Down Expand Up @@ -158,6 +162,7 @@ func (cxt *ConsensusContext) GetSignaturesCount() (count int) {

func (cxt *ConsensusContext) GetTransactionList() []*tx.Transaction {
Trace()
log.Info("len(cxt.txlist)=", len(cxt.txlist))
if cxt.txlist == nil {
cxt.txlist = []*tx.Transaction{}
fmt.Println("cxt.Transactions=", cxt.Transactions)
Expand Down Expand Up @@ -204,33 +209,40 @@ func (cxt *ConsensusContext) CheckTxHashesExist() bool {
return true
}

func (cxt *ConsensusContext) Reset(client cl.Client) {
func (cxt *ConsensusContext) Reset(client cl.Client, localNode net.Neter) {
Trace()
cxt.State = Initial
cxt.PrevHash = ledger.DefaultLedger.Blockchain.CurrentBlockHash()
cxt.Height = ledger.DefaultLedger.Blockchain.BlockHeight + 1
cxt.ViewNumber = 0
cxt.Miners = ledger.DefaultLedger.Blockchain.GetMiners()
cxt.MinerIndex = -1

miners, _ := localNode.GetMinersAddrs()
cxt.Owner = miners[0]
log.Debug("[Public Key] =", cxt.Owner)
sort.Sort(crypto.PubKeySlice(miners))
cxt.Miners = miners

minerLen := len(cxt.Miners)
cxt.PrimaryIndex = cxt.Height % uint32(minerLen)
cxt.TransactionHashes = nil
cxt.Signatures = make([][]byte, minerLen)
cxt.ExpectedView = make([]byte, minerLen)

log.Debug("[Consensus Reset] minerLen= ", minerLen)
log.Debug("[Consensus Miners Length] = ", minerLen)
for _, v := range cxt.Miners {
pubkey, _ := v.EncodePoint(true)
log.Debug("[Consensus Reset] Miners pub key = ", pubkey)
log.Debug("[Consensus Miners] = ", pubkey)
}

for i := 0; i < minerLen; i++ {
if client.ContainsAccount(cxt.Miners[i]) {
ac, _ := client.GetDefaultAccount()
if ac.PublicKey.X.Cmp(cxt.Miners[i].X) == 0 {
cxt.MinerIndex = i
break
}
}

log.Debug("cxt.MinerIndex = ", cxt.MinerIndex)
cxt.header = nil
}
11 changes: 3 additions & 8 deletions consensus/dbft/dbftService.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ func NewDbftService(client cl.Client, logDictionary string, localNet net.Neter)
Trace()

ds := &DbftService{
//localNode: localNode,
Client: client,
timer: time.NewTimer(time.Second * 15),
started: false,
Expand Down Expand Up @@ -89,9 +88,7 @@ func (ds *DbftService) AddTransaction(TX *tx.Transaction, needVerify bool) error
//if enough TXs already added to context, build block and sign/relay
if len(ds.context.TransactionHashes) == len(ds.context.Transactions) {

//Get Miner list
txlist := ds.context.GetTransactionList()
minerAddress, err := ledger.GetMinerAddress(ledger.DefaultLedger.Blockchain.GetMinersByTXs(txlist))
minerAddress, err := ledger.GetMinerAddress(ds.context.Miners)
if err != nil {
return NewDetailErr(err, ErrNoCode, "[DbftService] ,GetMinerAddress failed")
}
Expand Down Expand Up @@ -133,7 +130,6 @@ func (ds *DbftService) BlockPersistCompleted(v interface{}) {
ds.blockReceivedTime = time.Now()

go ds.InitializeConsensus(0)
//ds.InitializeConsensus(0)
}

func (ds *DbftService) CheckExpectedView(viewNumber byte) {
Expand Down Expand Up @@ -273,7 +269,7 @@ func (ds *DbftService) InitializeConsensus(viewNum byte) error {
log.Debug("[InitializeConsensus] viewNum: ", viewNum)

if viewNum == 0 {
ds.context.Reset(ds.Client)
ds.context.Reset(ds.Client, ds.localNet)
} else {
ds.context.ChangeView(viewNum)
}
Expand Down Expand Up @@ -554,7 +550,6 @@ func (ds *DbftService) Start() error {
ds.newInventorySubscriber = ds.localNet.GetEvent("consensus").Subscribe(events.EventNewInventory, ds.LocalNodeNewInventory)

go ds.InitializeConsensus(0)
//ds.InitializeConsensus(0)
return nil
}

Expand Down Expand Up @@ -626,7 +621,7 @@ func (ds *DbftService) Timeout() {
ds.context.Transactions = txMap

//build block and sign
ds.context.NextMiner, _ = ledger.GetMinerAddress(ledger.DefaultLedger.Blockchain.GetMinersByTXs(transactions))
ds.context.NextMiner, _ = ledger.GetMinerAddress(ds.context.Miners)
block := ds.context.MakeHeader()
account, _ := ds.Client.GetAccount(ds.context.Miners[ds.context.MinerIndex]) //TODO: handle error
ds.context.Signatures[ds.context.MinerIndex], _ = sig.SignBySigner(block, account)
Expand Down
26 changes: 24 additions & 2 deletions core/ledger/block.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package ledger

import (
. "GoOnchain/common"
"GoOnchain/common/log"
"GoOnchain/common/serialization"
"GoOnchain/core/contract/program"
tx "GoOnchain/core/transaction"
Expand Down Expand Up @@ -98,7 +99,7 @@ func (b *Block) Type() InventoryType {
return BLOCK
}

func GenesisBlockInit() (*Block, error) {
func GenesisBlockInit(miners []*crypto.PubKey) (*Block, error) {
genesisBlock := new(Block)
//blockdata
genesisBlockdata := new(Blockdata)
Expand All @@ -109,7 +110,8 @@ func GenesisBlockInit() (*Block, error) {
genesisBlockdata.Timestamp = uint32(tm.Unix())
genesisBlockdata.Height = uint32(0)
genesisBlockdata.ConsensusData = uint64(2083236893)
nextMiner, err := GetMinerAddress(StandbyMiners)

nextMiner, err := GetMinerAddress(miners)
if err != nil {
return nil, NewDetailErr(err, ErrNoCode, "[Block],GenesisBlockInit err with GetMinerAddress")
}
Expand Down Expand Up @@ -150,6 +152,26 @@ func GenesisBlockInit() (*Block, error) {

return genesisBlock, nil
}

func CreateGenesisBlock(miners []*crypto.PubKey) error {
genesisBlock, err := GenesisBlockInit(miners)
if err != nil {
log.Error("Init Genesis Block Error")
return err
}
err = genesisBlock.RebuildMerkleRoot()
if err != nil {
return err
}
hashx := genesisBlock.Hash()
genesisBlock.hash = &hashx
err = DefaultLedger.Blockchain.AddBlock(genesisBlock)
if err != nil {
return err
}
return nil
}

func (b *Block) RebuildMerkleRoot() error {
txs := b.Transcations
transactionHashes := []Uint256{}
Expand Down
29 changes: 0 additions & 29 deletions core/ledger/blockchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ package ledger
import (
. "GoOnchain/common"
"GoOnchain/common/log"
tx "GoOnchain/core/transaction"
"GoOnchain/crypto"
. "GoOnchain/errors"
"GoOnchain/events"
"errors"
Expand All @@ -26,19 +24,6 @@ func NewBlockchain() *Blockchain {
}
}

func NewBlockchainWithGenesisBlock() (*Blockchain, error) {
blockchain := NewBlockchain()
genesisBlock, err := GenesisBlockInit()
if err != nil {
return nil, NewDetailErr(err, ErrNoCode, "[Blockchain], NewBlockchainWithGenesisBlock failed.")
}
genesisBlock.RebuildMerkleRoot()
hashx := genesisBlock.Hash()
genesisBlock.hash = &hashx
blockchain.AddBlock(genesisBlock)
return blockchain, nil
}

func (bc *Blockchain) AddBlock(block *Block) error {
Trace()

Expand Down Expand Up @@ -100,20 +85,6 @@ func (bc *Blockchain) ContainsTransaction(hash Uint256) bool {
return true
}

func (bc *Blockchain) GetMinersByTXs(others []*tx.Transaction) []*crypto.PubKey {
//TODO: GetMiners()
//TODO: Just for TestUse

return StandbyMiners
}

func (bc *Blockchain) GetMiners() []*crypto.PubKey {
//TODO: GetMiners()
//TODO: Just for TestUse

return StandbyMiners
}

func (bc *Blockchain) CurrentBlockHash() Uint256 {
return DefaultLedger.Store.GetCurrentBlockHash()
}
1 change: 0 additions & 1 deletion core/ledger/ledger.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (
)

var DefaultLedger *Ledger
var StandbyMiners []*crypto.PubKey

// Ledger - the struct for onchainDNA ledger
type Ledger struct {
Expand Down
32 changes: 27 additions & 5 deletions crypto/crypto.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package crypto

import (
"GoOnchain/common/serialization"
"GoOnchain/crypto/p256r1"
"GoOnchain/crypto/sm2"
"GoOnchain/crypto/util"
Expand Down Expand Up @@ -107,25 +108,46 @@ func Verify(pubkey PubKey, data []byte, signature []byte) (bool, error) {
}

// Serialize ---
func (e *PubKey) Serialize(w io.Writer) {
//TODO: implement PubKey.serialize
func (e *PubKey) Serialize(w io.Writer) error {
buf := e.X.Bytes()
err := serialization.WriteVarBytes(w, buf)
if err != nil {
return err
}
buf = e.Y.Bytes()
err = serialization.WriteVarBytes(w, buf)
return err
}

// DeSerialize ---
func (e *PubKey) DeSerialize(r io.Reader) error {
//TODO
bufx, err := serialization.ReadVarBytes(r)
if err != nil {
return err
}
e.X = big.NewInt(0)
e.X = e.X.SetBytes(bufx)
bufy, err := serialization.ReadVarBytes(r)
if err != nil {
return err
}
e.Y = big.NewInt(0)
e.Y = e.Y.SetBytes(bufy)
return nil
}

type PubKeySlice []*PubKey

func (p PubKeySlice) Len() int { return len(p) }
func (p PubKeySlice) Less(i, j int) bool {
//TODO:PubKeySlice Less
r := p[i].X.Cmp(p[j].X)
if r <= 0 {
return true
}
return false
}
func (p PubKeySlice) Swap(i, j int) {
//TODO:PubKeySlice Swap
p[i], p[j] = p[j], p[i]
}

func Sha256(value []byte) []byte {
Expand Down
Loading

0 comments on commit fe5a0ac

Please sign in to comment.