ipld-eth-server/core/geth_blockchain.go

50 lines
1.4 KiB
Go
Raw Normal View History

package core
2017-10-23 18:58:33 +00:00
import (
"fmt"
"reflect"
"github.com/ethereum/go-ethereum"
2017-10-23 18:58:33 +00:00
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"golang.org/x/net/context"
)
2017-10-23 18:58:33 +00:00
type GethBlockchain struct {
client *ethclient.Client
observers []BlockchainObserver
subscription ethereum.Subscription
2017-10-23 18:58:33 +00:00
}
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(gethBlock *types.Block) {
block := GethBlockToCoreBlock(gethBlock)
2017-10-23 18:58:33 +00:00
for _, observer := range blockchain.observers {
observer.NotifyBlockAdded(block)
}
}
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()
sub, _ := blockchain.client.SubscribeNewHead(myContext, headers)
blockchain.subscription = sub
for header := range headers {
gethBlock, _ := blockchain.client.BlockByNumber(myContext, header.Number)
blockchain.notifyObservers(gethBlock)
2017-10-23 18:58:33 +00:00
}
}