Output the number of transactions when logging a new block

This commit is contained in:
Eric Meyer 2017-10-23 15:02:56 -05:00
parent cc05feee3f
commit 51ab23dd3a
3 changed files with 16 additions and 8 deletions

View File

@ -3,5 +3,6 @@ package core
import "math/big" import "math/big"
type Block struct { type Block struct {
Number *big.Int Number *big.Int
NumberOfTransactions int
} }

View File

@ -5,5 +5,5 @@ import "fmt"
type BlockchainLoggingObserver struct{} type BlockchainLoggingObserver struct{}
func (blockchainObserver BlockchainLoggingObserver) NotifyBlockAdded(block Block) { func (blockchainObserver BlockchainLoggingObserver) NotifyBlockAdded(block Block) {
fmt.Printf("New block was added: %d\n", block.Number) fmt.Printf("New block was added: %d, %d\n", block.Number, block.NumberOfTransactions)
} }

View File

@ -21,12 +21,18 @@ func NewGethBlockchain(ipcPath string) *GethBlockchain {
blockchain.client = client blockchain.client = client
return &blockchain return &blockchain
} }
func (blockchain GethBlockchain) notifyObservers(header *types.Header) { func (blockchain GethBlockchain) notifyObservers(getBlock *types.Block) {
block := Block{Number: header.Number} block := convertBlock(getBlock)
for _, observer := range blockchain.observers { for _, observer := range blockchain.observers {
observer.NotifyBlockAdded(block) observer.NotifyBlockAdded(block)
} }
} }
func convertBlock(gethBlock *types.Block) Block {
return Block{
Number: gethBlock.Number(),
NumberOfTransactions: len(gethBlock.Transactions()),
}
}
func (blockchain *GethBlockchain) RegisterObserver(observer BlockchainObserver) { func (blockchain *GethBlockchain) RegisterObserver(observer BlockchainObserver) {
fmt.Printf("Registering observer: %v\n", reflect.TypeOf(observer)) fmt.Printf("Registering observer: %v\n", reflect.TypeOf(observer))
@ -34,10 +40,11 @@ func (blockchain *GethBlockchain) RegisterObserver(observer BlockchainObserver)
} }
func (blockchain *GethBlockchain) SubscribeToEvents() { func (blockchain *GethBlockchain) SubscribeToEvents() {
blocks := make(chan *types.Header, 10) headers := make(chan *types.Header, 10)
myContext := context.Background() myContext := context.Background()
blockchain.client.SubscribeNewHead(myContext, blocks) blockchain.client.SubscribeNewHead(myContext, headers)
for block := range blocks { for header := range headers {
blockchain.notifyObservers(block) gethBlock, _ := blockchain.client.BlockByNumber(myContext, header.Number)
blockchain.notifyObservers(gethBlock)
} }
} }