ipld-eth-server/pkg/geth/blockchain.go

83 lines
2.2 KiB
Go
Raw Normal View History

package geth
2017-10-23 18:58:33 +00:00
import (
"math/big"
2018-01-10 21:54:36 +00:00
"strings"
2018-01-15 21:27:45 +00:00
"log"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common"
2017-10-23 18:58:33 +00:00
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/rpc"
"github.com/vulcanize/vulcanizedb/pkg/core"
"github.com/vulcanize/vulcanizedb/pkg/geth/node"
2017-10-23 18:58:33 +00:00
"golang.org/x/net/context"
)
type Blockchain struct {
client *ethclient.Client
readGethHeaders chan *types.Header
outputBlocks chan core.Block
newHeadSubscription ethereum.Subscription
node core.Node
}
func NewBlockchain(ipcPath string) *Blockchain {
blockchain := Blockchain{}
2018-01-15 21:27:45 +00:00
rpcClient, err := rpc.Dial(ipcPath)
if err != nil {
log.Println("Unable to connect to node")
2018-01-15 21:27:45 +00:00
log.Fatal(err)
}
client := ethclient.NewClient(rpcClient)
2018-01-10 21:54:36 +00:00
blockchain.node = node.Info(rpcClient)
if infura := isInfuraNode(ipcPath); infura {
blockchain.node.ID = "infura"
2018-01-10 21:54:36 +00:00
blockchain.node.ClientName = "infura"
}
blockchain.client = client
return &blockchain
}
2018-01-10 21:54:36 +00:00
func isInfuraNode(ipcPath string) bool {
if strings.Contains(ipcPath, "infura") {
return true
}
return false
}
func (blockchain *Blockchain) GetLogs(contract core.Contract, startingBlockNumber *big.Int, endingBlockNumber *big.Int) ([]core.Log, error) {
if endingBlockNumber == nil {
endingBlockNumber = startingBlockNumber
}
contractAddress := common.HexToAddress(contract.Hash)
fc := ethereum.FilterQuery{
FromBlock: startingBlockNumber,
ToBlock: endingBlockNumber,
Addresses: []common.Address{contractAddress},
}
gethLogs, err := blockchain.client.FilterLogs(context.Background(), fc)
if err != nil {
return []core.Log{}, err
}
2018-01-15 21:27:45 +00:00
logs := ToCoreLogs(gethLogs)
return logs, nil
}
func (blockchain *Blockchain) Node() core.Node {
return blockchain.node
2017-10-23 18:58:33 +00:00
}
func (blockchain *Blockchain) GetBlockByNumber(blockNumber int64) core.Block {
gethBlock, _ := blockchain.client.BlockByNumber(context.Background(), big.NewInt(blockNumber))
return ToCoreBlock(gethBlock, blockchain.client)
}
func (blockchain *Blockchain) LastBlock() *big.Int {
block, _ := blockchain.client.HeaderByNumber(context.Background(), nil)
return block.Number
}