Skip to content
Snippets Groups Projects
Commit 58ae5c27 authored by Miguel Montes's avatar Miguel Montes
Browse files

Cambios en algunas definiciones de tipos

Cambios en el manejo de argumentos de la línea de comandos
Cambios en el manejo de errores
parent b9f732de
No related branches found
No related tags found
No related merge requests found
...@@ -49,42 +49,42 @@ func (u *Uint64) UnmarshalJSON(b []byte) (err error) { ...@@ -49,42 +49,42 @@ func (u *Uint64) UnmarshalJSON(b []byte) (err error) {
return return
} }
// RPCTransaction represents a transaction that will serialize to the RPC representation of a transaction // RPCTransaction represents a transaction
type RPCTransaction struct { type RPCTransaction struct {
BlockHash string `json:"blockHash"` BlockHash common.Hash `json:"blockHash"`
BlockNumber Uint64 `json:"blockNumber"` BlockNumber Uint64 `json:"blockNumber"`
From string `json:"from"` From common.Address `json:"from"`
Gas Uint64 `json:"gas"` Gas Uint64 `json:"gas"`
GasPrice *BigInt `json:"gasPrice"` GasPrice *BigInt `json:"gasPrice"`
Hash string `json:"hash"` Hash common.Hash `json:"hash"`
Input string `json:"input"` Input string `json:"input"`
Nonce Uint64 `json:"nonce"` Nonce Uint64 `json:"nonce"`
To string `json:"to"` To common.Address `json:"to"`
TransactionIndex Uint64 `json:"transactionIndex"` TransactionIndex Uint64 `json:"transactionIndex"`
Value *BigInt `json:"value"` Value *BigInt `json:"value"`
V *BigInt `json:"v"` V *BigInt `json:"v"`
R *BigInt `json:"r"` R *BigInt `json:"r"`
S *BigInt `json:"s"` S *BigInt `json:"s"`
} }
type Block struct { type Block struct {
ParentHash string `json:"parentHash"` ParentHash common.Hash `json:"parentHash"`
Coinbase string `json:"miner"` Coinbase common.Address `json:"miner"`
Root string `json:"stateRoot"` Root common.Hash `json:"stateRoot"`
TxHash string `json:"transactionsRoot"` TxHash common.Hash `json:"transactionsRoot"`
ReceiptHash string `json:"receiptsRoot"` ReceiptHash common.Hash `json:"receiptsRoot"`
Bloom string `json:"logsBloom"` Bloom types.Bloom `json:"logsBloom"`
Difficulty Uint64 `json:"difficulty"` Difficulty Uint64 `json:"difficulty"`
Number Uint64 `json:"number"` Number Uint64 `json:"number"`
GasLimit Uint64 `json:"gasLimit"` GasLimit Uint64 `json:"gasLimit"`
GasUsed Uint64 `json:"gasUsed"` GasUsed Uint64 `json:"gasUsed"`
Time Uint64 `json:"timestamp"` Time Uint64 `json:"timestamp"`
Extra string `json:"extraData"` Extra []byte `json:"extraData"`
MixDigest string `json:"mixHash"` MixDigest common.Hash `json:"mixHash"`
Nonce Uint64 `json:"nonce"` Nonce Uint64 `json:"nonce"`
Transactions []RPCTransaction `json:"transactions"` Transactions []RPCTransaction `json:"transactions"`
TotalDifficulty Uint64 `json:"totalDifficulty"` TotalDifficulty Uint64 `json:"totalDifficulty"`
Signer string `json:"signer"` Signer common.Address `json:"signer"`
} }
type Snapshot struct { type Snapshot struct {
...@@ -200,7 +200,7 @@ func (node *Node) HeaderByNumber(blockNumber int64) types.Header { ...@@ -200,7 +200,7 @@ func (node *Node) HeaderByNumber(blockNumber int64) types.Header {
number string number string
resp types.Header resp types.Header
) )
if blockNumber < 0 { if blockNumber < 0 || blockNumber > node.BlockNumber() {
number = Latest number = Latest
} else { } else {
number = fmt.Sprintf("0x%x", blockNumber) number = fmt.Sprintf("0x%x", blockNumber)
...@@ -213,7 +213,7 @@ func (node *Node) BlockByNumber(blockNumber int64) (block Block) { ...@@ -213,7 +213,7 @@ func (node *Node) BlockByNumber(blockNumber int64) (block Block) {
var ( var (
number string number string
) )
if blockNumber < 0 { if blockNumber < 0 || blockNumber > node.BlockNumber() {
number = Latest number = Latest
} else { } else {
number = fmt.Sprintf("0x%x", blockNumber) number = fmt.Sprintf("0x%x", blockNumber)
...@@ -223,10 +223,12 @@ func (node *Node) BlockByNumber(blockNumber int64) (block Block) { ...@@ -223,10 +223,12 @@ func (node *Node) BlockByNumber(blockNumber int64) (block Block) {
return return
} }
func (node *Node) BlockSigner(blockNumber int64) (signer string) { func (node *Node) BlockSigner(blockNumber int64) (signer common.Address) {
if blockNumber == 0 { // we return an empty signer for genesis block
return
}
header := node.HeaderByNumber(blockNumber) header := node.HeaderByNumber(blockNumber)
signer, err := GetSigner(&header) signer = GetSigner(&header)
Check(err)
return return
} }
...@@ -241,7 +243,7 @@ func (node *Node) SnapshotAtHash(hash common.Hash) (snapshot Snapshot) { ...@@ -241,7 +243,7 @@ func (node *Node) SnapshotAtHash(hash common.Hash) (snapshot Snapshot) {
} }
func (node *Node) SnapshotAtBlock(blockNumber int64) (snapshot Snapshot) { func (node *Node) SnapshotAtBlock(blockNumber int64) (snapshot Snapshot) {
if blockNumber < 0 { if blockNumber < 0 || blockNumber >= node.BlockNumber() {
return node.GetSnapshot() return node.GetSnapshot()
} }
node.Call(&snapshot, "clique_getSnapshot", Int64ToHex(blockNumber)) node.Call(&snapshot, "clique_getSnapshot", Int64ToHex(blockNumber))
...@@ -353,7 +355,7 @@ func (node *Node) SealersStatus(blockNumber int64) (status map[string]*SealerSta ...@@ -353,7 +355,7 @@ func (node *Node) SealersStatus(blockNumber int64) (status map[string]*SealerSta
blockNumber = block.Number.Int64() blockNumber = block.Number.Int64()
until := Max(1, blockNumber-5*notSeen) until := Max(1, blockNumber-5*notSeen)
for notSeen > 0 { for notSeen > 0 {
signer, _ := GetSigner(&block) signer := BytesToHex(GetSigner(&block).Bytes())
if status[signer].LastBlock == 0 { if status[signer].LastBlock == 0 {
status[signer].LastBlock = block.Number.Int64() status[signer].LastBlock = block.Number.Int64()
status[signer].Time = block.Time.Uint64() status[signer].Time = block.Time.Uint64()
......
...@@ -66,12 +66,16 @@ func usage(errorCode int) { ...@@ -66,12 +66,16 @@ func usage(errorCode int) {
os.Exit(errorCode) os.Exit(errorCode)
} }
func parseFlags() { func parseFlags(allowAdditionalArgs bool) {
err := flags.Parse(os.Args[2:]) err := flags.Parse(os.Args[2:])
util.Check(err) util.Check(err)
if help { if help {
usage(0) usage(0)
} }
if flags.NArg() > 0 && !allowAdditionalArgs {
_, _ = fmt.Fprintln(os.Stderr, "Demasiados argumentos")
usage(1)
}
} }
func proposals() { func proposals() {
...@@ -79,7 +83,7 @@ func proposals() { ...@@ -79,7 +83,7 @@ func proposals() {
description = "Detalla el estado de las votaciones en curso" description = "Detalla el estado de las votaciones en curso"
setFlags() setFlags()
flags.Int64Var(&blockNumber, "block-number", latest, "Número del bloque en el cual se quiere conocer el estado de la propuesta (-1 para el último)") flags.Int64Var(&blockNumber, "block-number", latest, "Número del bloque en el cual se quiere conocer el estado de la propuesta (-1 para el último)")
parseFlags() parseFlags(false)
url = updateURL(url) url = updateURL(url)
node, err := bfa.Dial(url) node, err := bfa.Dial(url)
util.Check(err) util.Check(err)
...@@ -157,7 +161,7 @@ func sealers() { ...@@ -157,7 +161,7 @@ func sealers() {
flags.BoolVar(&balance, "balance", false, "Muestra el saldo del sellador (en Wei).") flags.BoolVar(&balance, "balance", false, "Muestra el saldo del sellador (en Wei).")
flags.BoolVar(&header, "header", true, "Muestra un encabezado en cada columna.") flags.BoolVar(&header, "header", true, "Muestra un encabezado en cada columna.")
flags.StringVar(&format, "format", "", "Formato del timestamp. Ignorado en formato json. Opciones: 'unix', 'rfc3339', 'long' ('YYYY-MM-DD hh:mm:ss'), 'short' ('hh:mm:ss') o un formato específico. Ejemplo 'DD/MM/YY hh.mm.ss'. También se admite el formato del paquete 'time' de go.") flags.StringVar(&format, "format", "", "Formato del timestamp. Ignorado en formato json. Opciones: 'unix', 'rfc3339', 'long' ('YYYY-MM-DD hh:mm:ss'), 'short' ('hh:mm:ss') o un formato específico. Ejemplo 'DD/MM/YY hh.mm.ss'. También se admite el formato del paquete 'time' de go.")
parseFlags() parseFlags(false)
if blockNumber == 0 { if blockNumber == 0 {
panic("El bloque génesis no tiene firmantes") panic("El bloque génesis no tiene firmantes")
} }
...@@ -263,13 +267,13 @@ func autovote() { ...@@ -263,13 +267,13 @@ func autovote() {
- No permite votar para eliminarse a uno mismo de la lista de selladores.`, minSigners, threshold) - No permite votar para eliminarse a uno mismo de la lista de selladores.`, minSigners, threshold)
flags.IntVar(&threshold, "threshold", voteThreshold, "Cantidad mínima de votos en una propuesta para habilitar el voto automático.") flags.IntVar(&threshold, "threshold", voteThreshold, "Cantidad mínima de votos en una propuesta para habilitar el voto automático.")
setFlags() setFlags()
parseFlags() parseFlags(false)
util.PanicIf(threshold < voteThreshold, "No se puede especificar una cantidad de votos inferior a %v.", voteThreshold) util.DieIf(threshold < voteThreshold, "No se puede especificar una cantidad de votos inferior a %v.", voteThreshold)
url = updateURL(url) url = updateURL(url)
node, err := bfa.Dial(url) node, err := bfa.Dial(url)
util.Check(err) util.Check(err)
defer node.Close() defer node.Close()
util.PanicIf(!node.IsSealer(bfa.Self), "Solo los selladores pueden votar") util.DieIf(!node.IsSealer(bfa.Self), "Solo los selladores pueden votar")
votes := node.Votes(latest) votes := node.Votes(latest)
genesisSigners := node.SealersAtBlock(0) genesisSigners := node.SealersAtBlock(0)
self, err := node.Coinbase() self, err := node.Coinbase()
...@@ -279,7 +283,7 @@ func autovote() { ...@@ -279,7 +283,7 @@ func autovote() {
removedSealers += 1 removedSealers += 1
} }
} }
util.PanicIf(len(votes.Signers)-removedSealers < minSigners, "No se puede emitir un voto automático que reduzca la cantidad de selladores por debajo de %v.", minSigners) util.DieIf(len(votes.Signers)-removedSealers < minSigners, "No se puede emitir un voto automático que reduzca la cantidad de selladores por debajo de %v.", minSigners)
for _, proposal := range votes.Proposals { for _, proposal := range votes.Proposals {
isSealer := util.Contains(votes.Signers, proposal) isSealer := util.Contains(votes.Signers, proposal)
switch { switch {
...@@ -317,12 +321,12 @@ func propose() { ...@@ -317,12 +321,12 @@ func propose() {
otherArgs = "[propuesta...]" otherArgs = "[propuesta...]"
setFlags() setFlags()
flags.BoolVar(&authorize, "authorize", true, "Sentido del voto (true: a favor, false: en contra).") flags.BoolVar(&authorize, "authorize", true, "Sentido del voto (true: a favor, false: en contra).")
parseFlags() parseFlags(true)
url = updateURL(url) url = updateURL(url)
node, err := bfa.Dial(url) node, err := bfa.Dial(url)
util.Check(err) util.Check(err)
defer node.Close() defer node.Close()
util.PanicIf(!node.IsSealer(bfa.Self), "Solo los selladores pueden votar") util.DieIf(!node.IsSealer(bfa.Self), "Solo los selladores pueden votar")
votes := node.Votes(latest) votes := node.Votes(latest)
if flags.NArg() == 0 { if flags.NArg() == 0 {
panic("No se especificaron candidatos por los cuales votar") panic("No se especificaron candidatos por los cuales votar")
...@@ -372,7 +376,7 @@ func status() { ...@@ -372,7 +376,7 @@ func status() {
} }
description = "Muestra el estado del nodo." description = "Muestra el estado del nodo."
setFlags() setFlags()
parseFlags() parseFlags(false)
url = updateURL(url) url = updateURL(url)
node, err := bfa.Dial(url) node, err := bfa.Dial(url)
util.Check(err) util.Check(err)
...@@ -402,7 +406,7 @@ func block() { ...@@ -402,7 +406,7 @@ func block() {
description = "Presenta la lista de selladores. Opcionalmente indica el último bloque sellado por cada uno." description = "Presenta la lista de selladores. Opcionalmente indica el último bloque sellado por cada uno."
setFlags() setFlags()
flags.Int64Var(&blockNumber, "block-number", latest, "Número del bloque en el cual se quiere conocer la lista de selladores (-1 para el último)") flags.Int64Var(&blockNumber, "block-number", latest, "Número del bloque en el cual se quiere conocer la lista de selladores (-1 para el último)")
parseFlags() parseFlags(false)
url = updateURL(url) url = updateURL(url)
node, err := bfa.Dial(url) node, err := bfa.Dial(url)
util.Check(err) util.Check(err)
...@@ -416,7 +420,7 @@ func snapshot() { ...@@ -416,7 +420,7 @@ func snapshot() {
description = "Muestra el snapshot en un bloque" description = "Muestra el snapshot en un bloque"
setFlags() setFlags()
flags.Int64Var(&blockNumber, "block-number", latest, "Número del bloque en el cual se quiere conocer la lista de selladores (-1 para el último)") flags.Int64Var(&blockNumber, "block-number", latest, "Número del bloque en el cual se quiere conocer la lista de selladores (-1 para el último)")
parseFlags() parseFlags(false)
url = updateURL(url) url = updateURL(url)
node, err := bfa.Dial(url) node, err := bfa.Dial(url)
util.Check(err) util.Check(err)
......
...@@ -6,7 +6,6 @@ import ( ...@@ -6,7 +6,6 @@ import (
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/crypto/sha3" "github.com/ethereum/go-ethereum/crypto/sha3"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"../util"
) )
func sigHash(header *types.Header) (hash common.Hash) { func sigHash(header *types.Header) (hash common.Hash) {
...@@ -33,12 +32,13 @@ func sigHash(header *types.Header) (hash common.Hash) { ...@@ -33,12 +32,13 @@ func sigHash(header *types.Header) (hash common.Hash) {
return hash return hash
} }
func GetSigner(header *types.Header) (signer string, err error) { func GetSigner(header *types.Header) (address common.Address) {
signature := header.Extra[len(header.Extra)-65:] signature := header.Extra[len(header.Extra)-65:]
hash := sigHash(header).Bytes() hash := sigHash(header).Bytes()
pubkey, err := crypto.Ecrecover(hash, signature) pubkey, err := crypto.Ecrecover(hash, signature)
address := make([]byte, 20) if err != nil {
copy(address, crypto.Keccak256(pubkey[1:])[12:]) panic(err)
signer = util.BytesToHex(address) }
copy(address[:], crypto.Keccak256(pubkey[1:])[12:])
return return
} }
...@@ -5,6 +5,7 @@ import ( ...@@ -5,6 +5,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"log"
"runtime" "runtime"
"strconv" "strconv"
) )
...@@ -29,7 +30,7 @@ func BytesToHex(b []byte) string { ...@@ -29,7 +30,7 @@ func BytesToHex(b []byte) string {
} }
func Int64ToHex(n int64) string { func Int64ToHex(n int64) string {
return "0x"+strconv.FormatInt(n,16) return "0x" + strconv.FormatInt(n, 16)
} }
func PrintDebug(prefix, suffix string) { func PrintDebug(prefix, suffix string) {
...@@ -51,24 +52,20 @@ func Max(a, b int64) int64 { ...@@ -51,24 +52,20 @@ func Max(a, b int64) int64 {
return b return b
} }
func PrintJson(s interface{}){ func PrintJson(s interface{}) {
v, err := json.MarshalIndent(s, "", " ") v, err := json.MarshalIndent(s, "", " ")
Check(err) Check(err)
fmt.Println(string(v)) fmt.Println(string(v))
return return
} }
func IsAddress(address string) bool { func IsAddress(address string) bool {
bytes, err := hex.DecodeString(address[2:]) bytes, err := hex.DecodeString(address[2:])
return err == nil && len(bytes) == common.AddressLength return err == nil && len(bytes) == common.AddressLength
} }
func PanicIf(cond bool, format string, args ...interface{}){ func DieIf(cond bool, format string, args ...interface{}) {
if cond { if cond {
panic(fmt.Sprintf(format, args...)) log.Fatalf(format, args...)
} }
} }
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment