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

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

View File

@ -5,5 +5,5 @@ import "fmt"
type BlockchainLoggingObserver struct{}
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
return &blockchain
}
func (blockchain GethBlockchain) notifyObservers(header *types.Header) {
block := Block{Number: header.Number}
func (blockchain GethBlockchain) notifyObservers(getBlock *types.Block) {
block := convertBlock(getBlock)
for _, observer := range blockchain.observers {
observer.NotifyBlockAdded(block)
}
}
func convertBlock(gethBlock *types.Block) Block {
return Block{
Number: gethBlock.Number(),
NumberOfTransactions: len(gethBlock.Transactions()),
}
}
func (blockchain *GethBlockchain) RegisterObserver(observer BlockchainObserver) {
fmt.Printf("Registering observer: %v\n", reflect.TypeOf(observer))
@ -34,10 +40,11 @@ func (blockchain *GethBlockchain) RegisterObserver(observer BlockchainObserver)
}
func (blockchain *GethBlockchain) SubscribeToEvents() {
blocks := make(chan *types.Header, 10)
headers := make(chan *types.Header, 10)
myContext := context.Background()
blockchain.client.SubscribeNewHead(myContext, blocks)
for block := range blocks {
blockchain.notifyObservers(block)
blockchain.client.SubscribeNewHead(myContext, headers)
for header := range headers {
gethBlock, _ := blockchain.client.BlockByNumber(myContext, header.Number)
blockchain.notifyObservers(gethBlock)
}
}