2017-10-23 15:56:29 +00:00
|
|
|
package core
|
|
|
|
|
2017-10-23 18:58:33 +00:00
|
|
|
import (
|
|
|
|
"fmt"
|
2017-10-25 22:24:38 +00:00
|
|
|
"reflect"
|
|
|
|
|
2017-10-24 14:24:07 +00:00
|
|
|
"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 15:56:29 +00:00
|
|
|
|
2017-10-23 18:58:33 +00:00
|
|
|
type GethBlockchain struct {
|
2017-10-24 14:24:07 +00:00
|
|
|
client *ethclient.Client
|
|
|
|
observers []BlockchainObserver
|
|
|
|
subscription ethereum.Subscription
|
2017-10-23 18:58:33 +00:00
|
|
|
}
|
2017-10-23 15:56:29 +00:00
|
|
|
|
2017-10-23 19:33:08 +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{}
|
2017-10-23 19:33:08 +00:00
|
|
|
client, _ := ethclient.Dial(ipcPath)
|
2017-10-23 18:58:33 +00:00
|
|
|
// TODO: handle error gracefully
|
|
|
|
blockchain.client = client
|
|
|
|
return &blockchain
|
|
|
|
}
|
2017-10-24 14:24:07 +00:00
|
|
|
|
2017-10-25 22:24:38 +00:00
|
|
|
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 15:56:29 +00:00
|
|
|
}
|
2017-10-24 14:24:07 +00:00
|
|
|
|
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 15:56:29 +00:00
|
|
|
|
2017-10-23 18:58:33 +00:00
|
|
|
func (blockchain *GethBlockchain) SubscribeToEvents() {
|
2017-10-23 20:02:56 +00:00
|
|
|
headers := make(chan *types.Header, 10)
|
2017-10-23 18:58:33 +00:00
|
|
|
myContext := context.Background()
|
2017-10-24 14:24:07 +00:00
|
|
|
sub, _ := blockchain.client.SubscribeNewHead(myContext, headers)
|
|
|
|
blockchain.subscription = sub
|
2017-10-23 20:02:56 +00:00
|
|
|
for header := range headers {
|
|
|
|
gethBlock, _ := blockchain.client.BlockByNumber(myContext, header.Number)
|
|
|
|
blockchain.notifyObservers(gethBlock)
|
2017-10-23 18:58:33 +00:00
|
|
|
}
|
2017-10-23 15:56:29 +00:00
|
|
|
}
|