Skip to content

Commit

Permalink
init : p2p gRPC
Browse files Browse the repository at this point in the history
  • Loading branch information
0xsharma committed Aug 5, 2023
1 parent 677ad30 commit 65bddd2
Show file tree
Hide file tree
Showing 14 changed files with 734 additions and 35 deletions.
8 changes: 8 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,11 @@ lintci-deps:

test:
$(GOTEST) --timeout 5m -shuffle=on ./...

devtools:
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
@type "protoc" 2> /dev/null || echo '\n\nPlease install protoc\n Linux : apt install -y protobuf-compiler\n Mac : brew install protobuf\n Windows : choco install protoc\n'

protoc:
protoc --go_out=. --go-grpc_out=. ./protos/*.proto
4 changes: 3 additions & 1 deletion cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,10 @@ func demoBlockchain() {
DBDir: dbPath,
StateDBDir: stateDbPath,
MinFee: big.NewInt(100),
RPCPort: ":6999",
RPCPort: ":1711",
BalanceAlloc: map[string]*big.Int{},
P2PPort: ":6060",
Peers: []string{"localhost:6061"},
}

chain := core.NewBlockchain(config)
Expand Down
3 changes: 3 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ type Config struct {
SignerPrivateKey *ecdsa.PrivateKey
Mine bool
BalanceAlloc map[string]*big.Int
P2PPort string
Peers []string
}

func DefaultConfig() *Config {
Expand All @@ -33,6 +35,7 @@ func DefaultConfig() *Config {
StateDBDir: stateDbPath,
MinFee: big.NewInt(100),
RPCPort: ":1711",
P2PPort: ":6060",
}

return cfg
Expand Down
58 changes: 33 additions & 25 deletions core/blockchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,64 +10,69 @@ import (
"github.com/0xsharma/compact-chain/consensus/pow"
"github.com/0xsharma/compact-chain/dbstore"
"github.com/0xsharma/compact-chain/executer"
"github.com/0xsharma/compact-chain/p2p"
"github.com/0xsharma/compact-chain/rpc"
"github.com/0xsharma/compact-chain/txpool"
"github.com/0xsharma/compact-chain/types"
"github.com/0xsharma/compact-chain/util"
)

type Blockchain struct {
LastBlock *types.Block
Consensus consensus.Consensus
Mutex *sync.RWMutex
LastHash *util.Hash
Db *dbstore.DB
StateDB *dbstore.DB
Txpool *txpool.TxPool
RPCServer *rpc.RPCServer
TxProcessor *executer.TxProcessor
Signer *util.Address
LastBlock *types.Block
Consensus consensus.Consensus
Mutex *sync.RWMutex
LastHash *util.Hash
BlockchainDb *dbstore.BlockchainDB
StateDB *dbstore.StateDB
Txpool *txpool.TxPool
RPCServer *rpc.RPCServer
TxProcessor *executer.TxProcessor
Signer *util.Address
}

// defaultConsensusDifficulty is the default difficulty for the proof of work consensus.
var defaultConsensusDifficulty = 10

// NewBlockchain creates a new blockchain with the given config.
func NewBlockchain(c *config.Config) *Blockchain {
db, err := dbstore.NewDB(c.DBDir)
dbInstance, err := dbstore.NewDBInstance(c.DBDir)
if err != nil {
panic(err)
}

stateDB, err := dbstore.NewDB(c.StateDBDir)
blockchainDB := dbstore.NewBlockchainDB(dbInstance)

stateDBInstance, err := dbstore.NewDBInstance(c.StateDBDir)
if err != nil {
panic(err)
}

stateDB := dbstore.NewStateDB(stateDBInstance)

var genesis, lastBlock *types.Block

lastBlockBytes, err := db.Get(dbstore.LastHashKey)
lastBlockHashBytes, err := blockchainDB.DB.Get(dbstore.LastHashKey)
if err != nil {
genesis = CreateGenesisBlock(c.BalanceAlloc, stateDB)
genesis = CreateGenesisBlock(c.BalanceAlloc, stateDB.DB)
lastHash := genesis.DeriveHash()

dbBatch := db.NewBatch()
dbBatch := blockchainDB.DB.NewBatch()

// Batch write to db
dbBatch.Put([]byte(dbstore.LastHashKey), lastHash.Bytes())
dbBatch.Put([]byte(dbstore.PrefixKey(dbstore.HashesKey, lastHash.String())), genesis.Serialize())
dbBatch.Put([]byte(dbstore.PrefixKey(dbstore.BlockNumberKey, genesis.Number.String())), lastHash.Bytes())

// Commit batch to db
err = db.WriteBatch(dbBatch)
err = blockchainDB.DB.WriteBatch(dbBatch)
if err != nil {
panic(err)
}

lastBlock = genesis
} else {
lastHash := util.ByteToHash(lastBlockBytes)
lastBlockBytes, err = db.Get(dbstore.PrefixKey(dbstore.HashesKey, lastHash.String()))
lastHash := util.ByteToHash(lastBlockHashBytes)
lastBlockBytes, err := blockchainDB.DB.Get(dbstore.PrefixKey(dbstore.HashesKey, lastHash.String()))
if err != nil {
panic(err)
}
Expand All @@ -78,7 +83,7 @@ func NewBlockchain(c *config.Config) *Blockchain {

if c.Mine && c.SignerPrivateKey != nil {
p := c.SignerPrivateKey.PublicKey
txProcessor = executer.NewTxProcessor(stateDB, c.MinFee, util.PublicKeyToAddress(&p))
txProcessor = executer.NewTxProcessor(stateDB.DB, c.MinFee, util.PublicKeyToAddress(&p))
}

var consensus consensus.Consensus
Expand All @@ -94,14 +99,17 @@ func NewBlockchain(c *config.Config) *Blockchain {
panic("Invalid consensus algorithm")
}

bc_txpool := txpool.NewTxPool(c.MinFee, stateDB)
bc_txpool := txpool.NewTxPool(c.MinFee, stateDB.DB)

rpcDomains := &rpc.RPCDomains{
TxPool: bc_txpool,
}
rpcServer := rpc.NewRPCServer(c.RPCPort, rpcDomains)

bc := &Blockchain{LastBlock: lastBlock, Consensus: consensus, Mutex: new(sync.RWMutex), Db: db, LastHash: lastBlock.DeriveHash(), StateDB: stateDB, Txpool: bc_txpool, TxProcessor: txProcessor, RPCServer: rpcServer}
bc := &Blockchain{LastBlock: lastBlock, Consensus: consensus, Mutex: new(sync.RWMutex), BlockchainDb: blockchainDB, LastHash: lastBlock.DeriveHash(), StateDB: stateDB, Txpool: bc_txpool, TxProcessor: txProcessor, RPCServer: rpcServer}

p2pServer := p2p.NewServer(c.P2PPort, c.Peers, stateDB, blockchainDB, bc_txpool)
go p2pServer.StartServer()

return bc
}
Expand All @@ -120,15 +128,15 @@ func (bc *Blockchain) AddBlock(data []byte, txs []*types.Transaction) {
// Mine block
minedBlock := bc.Consensus.Mine(block)

dbBatch := bc.Db.NewBatch()
dbBatch := bc.BlockchainDb.DB.NewBatch()

// Batch write to db
dbBatch.Put([]byte(dbstore.PrefixKey(dbstore.HashesKey, minedBlock.DeriveHash().String())), minedBlock.Serialize())
dbBatch.Put([]byte(dbstore.PrefixKey(dbstore.BlockNumberKey, minedBlock.Number.String())), minedBlock.DeriveHash().Bytes())
dbBatch.Put([]byte(dbstore.LastHashKey), minedBlock.DeriveHash().Bytes())

// Commit batch to db
err := bc.Db.WriteBatch(dbBatch)
err := bc.BlockchainDb.DB.WriteBatch(dbBatch)
if err != nil {
panic(err)
}
Expand Down Expand Up @@ -166,7 +174,7 @@ func (bc *Blockchain) Current() *types.Block {

// GetBlockByNumber returns the block with the given block number.
func (bc *Blockchain) GetBlockByNumber(b *big.Int) (*types.Block, error) {
hashBytes, err := bc.Db.Get(dbstore.PrefixKey(dbstore.BlockNumberKey, b.String()))
hashBytes, err := bc.BlockchainDb.DB.Get(dbstore.PrefixKey(dbstore.BlockNumberKey, b.String()))
if err != nil {
return nil, err
}
Expand All @@ -183,7 +191,7 @@ func (bc *Blockchain) GetBlockByNumber(b *big.Int) (*types.Block, error) {

// GetBlockByHash returns the block with the given block hash.
func (bc *Blockchain) GetBlockByHash(h *util.Hash) (*types.Block, error) {
blockBytes, err := bc.Db.Get(dbstore.PrefixKey(dbstore.HashesKey, h.String()))
blockBytes, err := bc.BlockchainDb.DB.Get(dbstore.PrefixKey(dbstore.HashesKey, h.String()))
if err != nil {
return nil, err
}
Expand Down
10 changes: 5 additions & 5 deletions core/blockchain_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func TestBlockchainStateBalance(t *testing.T) {
DBDir: t.TempDir(),
StateDBDir: t.TempDir(),
MinFee: big.NewInt(100),
RPCPort: ":6999",
RPCPort: ":1711",
BalanceAlloc: map[string]*big.Int{
"0xa52c981eee8687b5e4afd69aa5006548c24d7685": big.NewInt(1000000000000000000), // Allocating funds to 0xa52c981eee8687b5e4afd69aa5006548c24d7685
},
Expand Down Expand Up @@ -67,23 +67,23 @@ func TestBlockchainStateBalance(t *testing.T) {
fmt.Println("Number : ", chain.LastBlock.Number, "Hash : ", chain.LastBlock.DeriveHash().String(), "TxCount", len(chain.LastBlock.Transactions))

// Assertions
balanceSender, err := chain.StateDB.Get(dbstore.PrefixKey(dbstore.BalanceKey, ua.Address().String()))
balanceSender, err := chain.StateDB.DB.Get(dbstore.PrefixKey(dbstore.BalanceKey, ua.Address().String()))
if err != nil {
t.Fatal(err)
}

balanceSenderBig := new(big.Int).SetBytes(balanceSender)
assert.Equal(t, big.NewInt(999999999999997000), balanceSenderBig)

balanceTo1, err := chain.StateDB.Get(dbstore.PrefixKey(dbstore.BalanceKey, to1.String()))
balanceTo1, err := chain.StateDB.DB.Get(dbstore.PrefixKey(dbstore.BalanceKey, to1.String()))
if err != nil {
t.Fatal(err)
}

balanceTo1Big := new(big.Int).SetBytes(balanceTo1)
assert.Equal(t, big.NewInt(1000), balanceTo1Big)

balanceTo2, err := chain.StateDB.Get(dbstore.PrefixKey(dbstore.BalanceKey, to2.String()))
balanceTo2, err := chain.StateDB.DB.Get(dbstore.PrefixKey(dbstore.BalanceKey, to2.String()))
if err != nil {
t.Fatal(err)
}
Expand All @@ -93,7 +93,7 @@ func TestBlockchainStateBalance(t *testing.T) {

addressMiner := util.NewUnlockedAccount(config.SignerPrivateKey)

balanceMiner, err := chain.StateDB.Get(dbstore.PrefixKey(dbstore.BalanceKey, addressMiner.Address().String()))
balanceMiner, err := chain.StateDB.DB.Get(dbstore.PrefixKey(dbstore.BalanceKey, addressMiner.Address().String()))
if err != nil {
t.Fatal(err)
}
Expand Down
32 changes: 32 additions & 0 deletions dbstore/blockchainDB.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package dbstore

import (
"github.com/0xsharma/compact-chain/types"
"github.com/0xsharma/compact-chain/util"
)

type BlockchainDB struct {
DB *DB
}

func NewBlockchainDB(db *DB) *BlockchainDB {
return &BlockchainDB{DB: db}
}

func (bdb *BlockchainDB) GetLatestBlock() (*types.Block, error) {
lastBlockHashBytes, err := bdb.DB.Get(LastHashKey)
if err != nil {
return nil, err
}

lastHash := util.ByteToHash(lastBlockHashBytes)

lastBlockBytes, err := bdb.DB.Get(PrefixKey(HashesKey, lastHash.String()))
if err != nil {
return nil, err
}

latestBlock := types.DeserializeBlock(lastBlockBytes)

return latestBlock, nil
}
2 changes: 1 addition & 1 deletion dbstore/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ type DB struct {
}

// NewDB creates a new DB instance.
func NewDB(dbPath string) (*DB, error) {
func NewDBInstance(dbPath string) (*DB, error) {
db, err := leveldb.OpenFile(dbPath, nil)
if err != nil {
return nil, err
Expand Down
9 changes: 9 additions & 0 deletions dbstore/statedb.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package dbstore

type StateDB struct {
DB *DB
}

func NewStateDB(db *DB) *StateDB {
return &StateDB{DB: db}
}
10 changes: 10 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,16 @@ require (
github.com/spf13/cobra v1.6.1
github.com/stretchr/testify v1.8.2
github.com/syndtr/goleveldb v1.0.0
google.golang.org/grpc v1.57.0
google.golang.org/protobuf v1.31.0
)

require (
github.com/golang/protobuf v1.5.3 // indirect
golang.org/x/net v0.9.0 // indirect
golang.org/x/sys v0.7.0 // indirect
golang.org/x/text v0.9.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20230525234030-28d5490b6b19 // indirect
)

require (
Expand Down
23 changes: 20 additions & 3 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,13 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db h1:woRePGFeVFfLKN/pOkfl+p/TAqKOfFu+7KPlMVpok/w=
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
Expand All @@ -34,13 +39,25 @@ github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/syndtr/goleveldb v1.0.0 h1:fBdIW9lB4Iz0n9khmH8w27SJ3QEJ7+IgjPEwGSZiFdE=
github.com/syndtr/goleveldb v1.0.0/go.mod h1:ZVVdQEZoIme9iO1Ch2Jdy24qqXrMMOU6lpPAyBWyWuQ=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd h1:nTDtHvHSdCn1m6ITfMRqtOd/9+7a3s8RBNOZ3eYZzJA=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM=
golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e h1:o3PsSEY8E4eXWkXrIP9YJALUkVZqzHJT5DOasTyn8Vs=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU=
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/genproto/googleapis/rpc v0.0.0-20230525234030-28d5490b6b19 h1:0nDDozoAU19Qb2HwhXadU8OcsiO/09cnTqhUtq2MEOM=
google.golang.org/genproto/googleapis/rpc v0.0.0-20230525234030-28d5490b6b19/go.mod h1:66JfowdXAEgad5O9NnYcsNPLCPZJD++2L9X0PCMODrA=
google.golang.org/grpc v1.57.0 h1:kfzNeI/klCGD2YPMUlaGNT3pxvYfga7smW3Vth8Zsiw=
google.golang.org/grpc v1.57.0/go.mod h1:Sd+9RMTACXwmub0zcNY2c4arhtrbBYD1AUHI/dt16Mo=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8=
google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4=
Expand Down
Loading

0 comments on commit 65bddd2

Please sign in to comment.