2017-10-25 15:57:59 +00:00
|
|
|
package core
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/jmoiron/sqlx"
|
|
|
|
_ "github.com/lib/pq"
|
|
|
|
)
|
|
|
|
|
|
|
|
type BlockchainDBObserver struct {
|
|
|
|
Db *sqlx.DB
|
|
|
|
}
|
|
|
|
|
|
|
|
func (observer BlockchainDBObserver) NotifyBlockAdded(block Block) {
|
2017-10-31 15:36:37 +00:00
|
|
|
insertedBlockId := saveBlock(observer, block)
|
|
|
|
saveTransactions(insertedBlockId, block.Transactions, observer)
|
|
|
|
}
|
|
|
|
|
|
|
|
func saveBlock(observer BlockchainDBObserver, block Block) int64 {
|
|
|
|
insertedBlock := observer.Db.QueryRow("Insert INTO blocks "+
|
2017-10-27 20:29:55 +00:00
|
|
|
"(block_number, block_gaslimit, block_gasused, block_time) "+
|
2017-10-31 15:36:37 +00:00
|
|
|
"VALUES ($1, $2, $3, $4) RETURNING id",
|
2017-10-31 17:51:05 +00:00
|
|
|
block.Number, block.GasLimit, block.GasUsed, block.Time)
|
2017-10-31 15:36:37 +00:00
|
|
|
var blockId int64
|
|
|
|
insertedBlock.Scan(&blockId)
|
|
|
|
return blockId
|
2017-10-31 13:58:04 +00:00
|
|
|
}
|
|
|
|
|
2017-10-31 15:36:37 +00:00
|
|
|
func saveTransactions(blockId int64, transactions []Transaction, observer BlockchainDBObserver) {
|
|
|
|
for _, transaction := range transactions {
|
|
|
|
observer.Db.MustExec("Insert INTO transactions "+
|
|
|
|
"(block_id, tx_hash, tx_nonce, tx_to, tx_gaslimit, tx_gasprice, tx_value) VALUES ($1, $2, $3, $4, $5, $6, $7)",
|
|
|
|
blockId, transaction.Hash, transaction.Nonce, transaction.To, transaction.GasLimit, transaction.GasPrice, transaction.Value)
|
|
|
|
}
|
2017-10-25 15:57:59 +00:00
|
|
|
}
|