Implement GethBlockchain

This commit is contained in:
Eric Meyer 2017-10-23 13:58:33 -05:00
parent de2cb3b5cc
commit de0bdff579
6 changed files with 46 additions and 10 deletions

View File

@ -2,4 +2,5 @@ package core
type Blockchain interface {
RegisterObserver(observer BlockchainObserver)
SubscribeToEvents()
}

View File

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

View File

@ -12,6 +12,11 @@ import (
var _ = Describe("The fake blockchain", func() {
It("conforms to the Blockchain interface", func() {
var blockchain core.Blockchain = &fakes.Blockchain{}
Expect(blockchain).ShouldNot(BeNil())
})
It("lets the only observer know when a block was added", func() {
blockchain := fakes.Blockchain{}
blockchainObserver := &fakes.BlockchainObserver{}

View File

@ -1,14 +1,43 @@
package core
import "fmt"
import (
"fmt"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"golang.org/x/net/context"
"reflect"
)
type GethBlockchain struct{}
type GethBlockchain struct {
client *ethclient.Client
observers []BlockchainObserver
}
func NewGethBlockchain() *GethBlockchain {
fmt.Println("Creating Gethblockchain")
return &GethBlockchain{}
fmt.Println("Creating Geth Blockchain")
blockchain := GethBlockchain{}
client, _ := ethclient.Dial("/var/folders/b3/z7fhy7cs06q8d7y3_pwwt4x40000gn/T/ethereum_dev_mode/geth.ipc")
// TODO: handle error gracefully
blockchain.client = client
return &blockchain
}
func (blockchain GethBlockchain) notifyObservers(header *types.Header) {
block := Block{Number: header.Number}
for _, observer := range blockchain.observers {
observer.NotifyBlockAdded(block)
}
}
func (blockchain *GethBlockchain) RegisterObserver(_ BlockchainObserver) {
func (blockchain *GethBlockchain) RegisterObserver(observer BlockchainObserver) {
fmt.Printf("Registering observer: %v\n", reflect.TypeOf(observer))
blockchain.observers = append(blockchain.observers, observer)
}
func (blockchain *GethBlockchain) SubscribeToEvents() {
blocks := make(chan *types.Header, 10)
myContext := context.Background()
blockchain.client.SubscribeNewHead(myContext, blocks)
for block := range blocks {
blockchain.notifyObservers(block)
}
}

View File

@ -17,3 +17,6 @@ func (blockchain *Blockchain) AddBlock(block core.Block) {
observer.NotifyBlockAdded(block)
}
}
func (_ *Blockchain) SubscribeToEvents() {
}

View File

@ -1,13 +1,11 @@
package main
import (
"fmt"
"github.com/8thlight/vulcanizedb/core"
)
func main() {
fmt.Println("Starting connection")
var blockchain core.Blockchain = core.NewGethBlockchain()
blockchain.RegisterObserver(core.BlockchainLoggingObserver{})
blockchain.SubscribeToEvents()
}