ipld-eth-server/core/geth_blockchain.go

51 lines
1.4 KiB
Go
Raw Normal View History

package core
2017-10-23 18:58:33 +00:00
import (
"fmt"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"golang.org/x/net/context"
"reflect"
)
2017-10-23 18:58:33 +00:00
type GethBlockchain struct {
client *ethclient.Client
observers []BlockchainObserver
}
func NewGethBlockchain(ipcPath string) *GethBlockchain {
fmt.Printf("Creating Geth Blockchain to: %s\n", ipcPath)
2017-10-23 18:58:33 +00:00
blockchain := GethBlockchain{}
client, _ := ethclient.Dial(ipcPath)
2017-10-23 18:58:33 +00:00
// TODO: handle error gracefully
blockchain.client = client
return &blockchain
}
func (blockchain GethBlockchain) notifyObservers(getBlock *types.Block) {
block := convertBlock(getBlock)
2017-10-23 18:58:33 +00:00
for _, observer := range blockchain.observers {
observer.NotifyBlockAdded(block)
}
}
func convertBlock(gethBlock *types.Block) Block {
return Block{
Number: gethBlock.Number(),
NumberOfTransactions: len(gethBlock.Transactions()),
}
}
2017-10-23 18:58:33 +00:00
func (blockchain *GethBlockchain) RegisterObserver(observer BlockchainObserver) {
fmt.Printf("Registering observer: %v\n", reflect.TypeOf(observer))
blockchain.observers = append(blockchain.observers, observer)
}
2017-10-23 18:58:33 +00:00
func (blockchain *GethBlockchain) SubscribeToEvents() {
headers := make(chan *types.Header, 10)
2017-10-23 18:58:33 +00:00
myContext := context.Background()
blockchain.client.SubscribeNewHead(myContext, headers)
for header := range headers {
gethBlock, _ := blockchain.client.BlockByNumber(myContext, header.Number)
blockchain.notifyObservers(gethBlock)
2017-10-23 18:58:33 +00:00
}
}