Allgemeine nützliche JavaScript-Schnipsel für geth

In Geth können Sie jede .jsDatei laden.

Ich habe dieses hier im Wiki entdeckt, das mir sehr gefällt:

function checkAllBalances() { 
  var i =0; 
  eth.accounts.forEach( function(e){
    console.log("  eth.accounts["+i+"]: " +  e + " \tbalance: " + web3.fromWei(eth.getBalance(e), "ether") + " ether"); 
    i++; 
  })
};

Verwenden Sie häufig andere? Eine Art Aufbewahrungsort für „Klassiker“ oder „Must-Have“ wäre eine großartige Ressource.

Hier habe ich alle Skripte zusammengefasst und daraus eine einzige Datei erstellt niksmac/ethereum-scripts
Ich verstehe also nicht, wie wir diese Skripte laden. Ich schätze, ich speichere das einzelne Skript, das ich verwenden möchte, als .js-Datei. Aber wie lade ich es dann in Geth?
Bei mir gibt es nur true zurück, wenn ich von einem anderen Endgerät aus anrufe. Es ist also woking, aber es werden keine Salden zurückgegeben

Antworten (12)

Skript zum Suchen von Transaktionen zu/von einem Konto

Verwendungszweck

Finden Sie alle Transaktionen zu/von eth.accounts[0]innerhalb der letzten 1.000 Blöcke:

> getTransactionsByAccount(eth.accounts[0])

Finden Sie alle Transaktionen zum/vom Konto von The DAO0xbb9bc244d798123fde783fcc1c72d3bb8c189413 zwischen den Blöcken 1.432.400 und 1.432.423:

> getTransactionsByAccount("0xbb9bc244d798123fde783fcc1c72d3bb8c189413", 1432400, 1432423)

Finden Sie alle Transaktionen zu/von jedem Konto in den letzten 1000 Blöcken:

> getTransactionsByAccount("*")


Das Skript

function getTransactionsByAccount(myaccount, startBlockNumber, endBlockNumber) {
  if (endBlockNumber == null) {
    endBlockNumber = eth.blockNumber;
    console.log("Using endBlockNumber: " + endBlockNumber);
  }
  if (startBlockNumber == null) {
    startBlockNumber = endBlockNumber - 1000;
    console.log("Using startBlockNumber: " + startBlockNumber);
  }
  console.log("Searching for transactions to/from account \"" + myaccount + "\" within blocks "  + startBlockNumber + " and " + endBlockNumber);

  for (var i = startBlockNumber; i <= endBlockNumber; i++) {
    if (i % 1000 == 0) {
      console.log("Searching block " + i);
    }
    var block = eth.getBlock(i, true);
    if (block != null && block.transactions != null) {
      block.transactions.forEach( function(e) {
        if (myaccount == "*" || myaccount == e.from || myaccount == e.to) {
          console.log("  tx hash          : " + e.hash + "\n"
            + "   nonce           : " + e.nonce + "\n"
            + "   blockHash       : " + e.blockHash + "\n"
            + "   blockNumber     : " + e.blockNumber + "\n"
            + "   transactionIndex: " + e.transactionIndex + "\n"
            + "   from            : " + e.from + "\n" 
            + "   to              : " + e.to + "\n"
            + "   value           : " + e.value + "\n"
            + "   time            : " + block.timestamp + " " + new Date(block.timestamp * 1000).toGMTString() + "\n"
            + "   gasPrice        : " + e.gasPrice + "\n"
            + "   gas             : " + e.gas + "\n"
            + "   input           : " + e.input);
        }
      })
    }
  }
}


Beispiel

Transaktionen zu/von eth.accounts[0]Adresse finden:

> getTransactionsByAccount(eth.accounts[0])
Using endBlockNumber: 1864
Using startBlockNumber: 864
Searching for transactions to/from account "0xa7857047907d53a2e494d5f311b4b586dc6a96d2" within blocks 864 and 1864
Searching block 1000
  tx hash          : 0x3c3bc3c456a84e20cf0077f9aa5ce363d3b12bca18d01000a750288c2e76401e
   nonce           : 44
   blockHash       : 0xef2d15775908951fc61f9a83b53c00cf2cde4e0def93e20544f784441c6178db
   blockNumber     : 1582
   transactionIndex: 0
   from            : 0xa7857047907d53a2e494d5f311b4b586dc6a96d2
   to              : null
   value           : 0
   time            : 1470459255 Sat, 06 Aug 2016 04:54:15 GMT
   gasPrice        : 20000000000
   gas             : 24615
   input           : 0x6060604052600a8060106000396000f360606040526008565b00
  tx hash          : 0xc255cdbf477452eb8922d8230889f7cc08b9deed4695378aba3d97906071ce5f
   nonce           : 45
   blockHash       : 0x987a8214af96bb1530b97fe09da8f8168679e42c9efb4defee50800f2067d6d8
   blockNumber     : 1587
   transactionIndex: 0
   from            : 0xa7857047907d53a2e494d5f311b4b586dc6a96d2
   to              : null
   value           : 0
   time            : 1470459409 Sat, 06 Aug 2016 04:56:49 GMT
   gasPrice        : 20000000000
   gas             : 24615
   input           : 0x6060604052600a8060106000396000f360606040526008565b00
...
@KalyanKumar, ich habe Ihre Bearbeitung abgelehnt, da das true im eth.getBlock(i, true);Funktionsaufruf alle Transaktionsobjekte zurückgibt, sodass Sie die map-Funktion nicht benötigen, um die Transaktionsobjekte erneut abzurufen.
Es sieht großartig aus, außer dass mindestens 1000 Blöcke erwartet werden. In meinem Testaufbau waren es nicht so viele. Zeile 7 sollte sein startBlockNumber = Math.max(endBlockNumber - 1000,0);.
@VikramRao, gibt es einen Grund, warum Sie es nicht auf weniger als tausend ändern können?
@RameshPareek sicher, dass Sie die Stapelgröße auswählen können. batch sizeIn meinem Fall würde das Skript nicht funktionieren , wenn angenommen wird, dass es weniger als (1000 in diesem Beispiel) gibt, und daher habe ich eine hinzugefügt min.
Ich denke, das ist trivial.
@TheOfficiousBokkyPooBah Ist es möglich, dieses Skript in einem Nodejs auszuführen? ethWelche Bibliothek können wir verwenden, die dem Objekt in Ihrem Code ähnlich ist ?
Wie finde ich eine für mehr als 1000 Konten?
Achtung, eth.getBlockgibt ein Versprechen zurück.
eth.accountsgeht hier nicht. Verwenden Sie eth.getAccounts(callback).

1. Meinen Sie nur, wenn es Transaktionen gibt!

var mining_threads = 1

function checkWork() {
    if (eth.getBlock("pending").transactions.length > 0) {
        if (eth.mining) return;
        console.log("== Pending transactions! Mining...");
        miner.start(mining_threads);
    } else {
        miner.stop(0);  // This param means nothing
        console.log("== No transactions! Mining stopped.");
    }
}

eth.filter("latest", function(err, block) { checkWork(); });
eth.filter("pending", function(err, block) { checkWork(); });

checkWork();

2. Holen Sie sich einige Daten von Geth, ohne den Knoten zu starten.

$ geth --exec "eth.accounts" console 2>/dev/null

["0x0000000000000000000000000000000000000000"]

3. Sehen Sie sich eine Transaktion an

function printTransaction(txHash) {
  var tx = eth.getTransaction(txHash);
  if (tx != null) {
    console.log("  tx hash          : " + tx.hash + "\n"
      + "   nonce           : " + tx.nonce + "\n"
      + "   blockHash       : " + tx.blockHash + "\n"
      + "   blockNumber     : " + tx.blockNumber + "\n"
      + "   transactionIndex: " + tx.transactionIndex + "\n"
      + "   from            : " + tx.from + "\n" 
      + "   to              : " + tx.to + "\n"
      + "   value           : " + tx.value + "\n"
      + "   gasPrice        : " + tx.gasPrice + "\n"
      + "   gas             : " + tx.gas + "\n"
      + "   input           : " + tx.input);
  }
}

4. Drucken Sie die Details eines Blocks

function printBlock(block) {
  console.log("Block number     : " + block.number + "\n"
    + " hash            : " + block.hash + "\n"
    + " parentHash      : " + block.parentHash + "\n"
    + " nonce           : " + block.nonce + "\n"
    + " sha3Uncles      : " + block.sha3Uncles + "\n"
    + " logsBloom       : " + block.logsBloom + "\n"
    + " transactionsRoot: " + block.transactionsRoot + "\n"
    + " stateRoot       : " + block.stateRoot + "\n"
    + " miner           : " + block.miner + "\n"
    + " difficulty      : " + block.difficulty + "\n"
    + " totalDifficulty : " + block.totalDifficulty + "\n"
    + " extraData       : " + block.extraData + "\n"
    + " size            : " + block.size + "\n"
    + " gasLimit        : " + block.gasLimit + "\n"
    + " gasUsed         : " + block.gasUsed + "\n"
    + " timestamp       : " + block.timestamp + "\n"
    + " transactions    : " + block.transactions + "\n"
    + " uncles          : " + block.uncles);
    if (block.transactions != null) {
      console.log("--- transactions ---");
      block.transactions.forEach( function(e) {
        printTransaction(e);
      })
    }
}

5. Überprüfen Sie alle Salden

function checkAllBalances() { 
 var i =0; 
 eth.accounts.forEach( function(e){
    console.log("  eth.accounts["+i+"]: " +  e + " \tbalance: " +    web3.fromWei(eth.getBalance(e), "ether") + " ether"); 
  i++; 
 })
};

Quellen

  1. https://github.com/ethereum/go-ethereum/wiki/bitchin-tricks
  2. https://ethereum.stackexchange.com/a/2928/259
@Nikhil M. Ich habe das Beispiel ausprobiert, das Sie für "Mine nur bei Transaktionen angegeben haben!" Aber ich kann den Befehl "miner.start(2)" nicht verwenden. Sieht so aus, als ob ich eine Bibliothek brauche, aber sicher ist sie nicht in web3.js vorhanden. Danke im Voraus.
@Sushant welcher Fehler?
checkWork() ist nicht zuverlässig. Gelegentlich beobachte ich, dass txs ausstehen, aber das Mining nicht beginnt. ZB eth.getBlock("pending").transactions.length == 0, eth.pendingTransactions.length == 3, aber eth.mining == false
@sinoTrinity, es ist ein altes Skript, Sie können es nach Bedarf verbessern.
Vielleicht zu ändern eth.getBlock("pending").transactions.length > 0 || eth.pendingTransactions.length > 0? Das habe ich aber nicht verifiziert.
Die letzte Version von github.com/ethereum/go-ethereum/wiki/bitchin-tricks ist unter der Commit-ID 34cfee511a49cb3a01a51380be18212f20a01933 verfügbar. Die aktuelle Version enthält diese Datei nicht.

Skript zum Finden einer Transaktionsanzahl ungleich Null in einer Reihe von Blöcken

(Aktualisierung 22.04.2016)

Hier ist ein Skript, um die Anzahl der Transaktionen zwischen einer Startblocknummer und einer Endblocknummer zu überprüfen:

function checkTransactionCount(startBlockNumber, endBlockNumber) {
  console.log("Searching for non-zero transaction counts between blocks "  + startBlockNumber + " and " + endBlockNumber);

  for (var i = startBlockNumber; i <= endBlockNumber; i++) {
    var block = eth.getBlock(i);
    if (block != null) {
      if (block.transactions != null && block.transactions.length != 0) {
        console.log("Block #" + i + " has " + block.transactions.length + " transactions")
      }
    }
  }
}

Das Ausführen der Skripte für die Blöcke 1 bis 46146 zeigt die folgenden Ergebnisse - es gibt keine Transaktionen!:

> checkTransactionCount(1, 46146)
Searching for non-zero transaction counts between blocks 1 and 46146
undefined

Lassen Sie uns überprüfen, ob das Skript wie erwartet funktioniert:

> eth.blockNumber
1382234
> checkTransactionCount(1382224, 1382234)
Searching for non-zero transaction counts between blocks 1382224 and 1382234
Block #1382224 has 4 transactions
Block #1382225 has 2 transactions
Block #1382226 has 4 transactions
Block #1382227 has 6 transactions
Block #1382228 has 17 transactions
Block #1382231 has 2 transactions
Block #1382234 has 1 transactions
undefined

In 46147 bis 46200 sind einige Transaktionen enthalten:

> checkTransactionCount(46147, 46200)
Searching for non-zero transaction counts between blocks 46147 and 46200
Block #46147 has 1 transactions
Block #46169 has 1 transactions
Block #46170 has 1 transactions
Block #46194 has 1 transactions
undefined
Achtung, eth.getBlock gibt ein Promise zurück.

Skript, um abgebaute Blöcke und Onkel zu finden + Transaktionen aufzulisten

Hier sind meine Skripte zum Überprüfen und Drucken von Blöcken, Onkeln und Transaktionen. Dies wurde ursprünglich als Antwort auf die Frage geschrieben, wie ich weiß, ob ein eingereichter Block ein Onkel wurde? .

Ich habe sie separat aufgeführt, um das Lesen zu erleichtern. Wenn Sie beabsichtigen, es in zu verwenden geth, möchten Sie wahrscheinlich die folgenden 5 Funktionen in einer einzigen Datei verketten, um sie einfach in die gethKonsole kopieren und einfügen zu können. Und entfernen Sie einfach das Feld, das Sie nicht sehen müssen.

printTransaction(txHash)

function printTransaction(txHash) {
  var tx = eth.getTransaction(txHash);
  if (tx != null) {
    console.log("  tx hash          : " + tx.hash + "\n"
      + "   nonce           : " + tx.nonce + "\n"
      + "   blockHash       : " + tx.blockHash + "\n"
      + "   blockNumber     : " + tx.blockNumber + "\n"
      + "   transactionIndex: " + tx.transactionIndex + "\n"
      + "   from            : " + tx.from + "\n" 
      + "   to              : " + tx.to + "\n"
      + "   value           : " + tx.value + "\n"
      + "   gasPrice        : " + tx.gasPrice + "\n"
      + "   gas             : " + tx.gas + "\n"
      + "   input           : " + tx.input);
  }
}

printBlock(block)

function printBlock(block) {
  console.log("Block number     : " + block.number + "\n"
    + " hash            : " + block.hash + "\n"
    + " parentHash      : " + block.parentHash + "\n"
    + " nonce           : " + block.nonce + "\n"
    + " sha3Uncles      : " + block.sha3Uncles + "\n"
    + " logsBloom       : " + block.logsBloom + "\n"
    + " transactionsRoot: " + block.transactionsRoot + "\n"
    + " stateRoot       : " + block.stateRoot + "\n"
    + " miner           : " + block.miner + "\n"
    + " difficulty      : " + block.difficulty + "\n"
    + " totalDifficulty : " + block.totalDifficulty + "\n"
    + " extraData       : " + block.extraData + "\n"
    + " size            : " + block.size + "\n"
    + " gasLimit        : " + block.gasLimit + "\n"
    + " gasUsed         : " + block.gasUsed + "\n"
    + " timestamp       : " + block.timestamp + "\n"
    + " transactions    : " + block.transactions + "\n"
    + " uncles          : " + block.uncles);
    if (block.transactions != null) {
      console.log("--- transactions ---");
      block.transactions.forEach( function(e) {
        printTransaction(e);
      })
    }
}

printOnkel(Block, OnkelNummer, Onkel)

function printUncle(block, uncleNumber, uncle) {
  console.log("Block number     : " + block.number + " , uncle position: " + uncleNumber + "\n"
    + " Uncle number    : " + uncle.number + "\n"
    + " hash            : " + uncle.hash + "\n"
    + " parentHash      : " + uncle.parentHash + "\n"
    + " nonce           : " + uncle.nonce + "\n"
    + " sha3Uncles      : " + uncle.sha3Uncles + "\n"
    + " logsBloom       : " + uncle.logsBloom + "\n"
    + " transactionsRoot: " + uncle.transactionsRoot + "\n"
    + " stateRoot       : " + uncle.stateRoot + "\n"
    + " miner           : " + uncle.miner + "\n"
    + " difficulty      : " + uncle.difficulty + "\n"
    + " totalDifficulty : " + uncle.totalDifficulty + "\n"
    + " extraData       : " + uncle.extraData + "\n"
    + " size            : " + uncle.size + "\n"
    + " gasLimit        : " + uncle.gasLimit + "\n"
    + " gasUsed         : " + uncle.gasUsed + "\n"
    + " timestamp       : " + uncle.timestamp + "\n"
    + " transactions    : " + uncle.transactions + "\n");
}

getMinedBlocks(Miner, startBlockNumber, endBlockNumber)

Wenn startBlockNumbernichts angegeben ist, werden standardmäßig die letzten 10.000 Blöcke verwendet. Das Scannen dauert einige Zeit. Reduzieren Sie diese Zahl daher auf 1000, um die Scanzeit zu verkürzen.

Wenn endBlockNumbernicht angegeben, wird standardmäßig die neueste Blocknummer verwendet.

function getMinedBlocks(miner, startBlockNumber, endBlockNumber) {
  if (endBlockNumber == null) {
    endBlockNumber = eth.blockNumber;
    console.log("Using endBlockNumber: " + endBlockNumber);
  }
  if (startBlockNumber == null) {
    startBlockNumber = endBlockNumber - 10000;
    console.log("Using startBlockNumber: " + startBlockNumber);
  }
  console.log("Searching for miner \"" + miner + "\" within blocks "  + startBlockNumber + " and " + endBlockNumber + "\"");

  for (var i = startBlockNumber; i <= endBlockNumber; i++) {
    if (i % 1000 == 0) {
      console.log("Searching block " + i);
    }
    var block = eth.getBlock(i);
    if (block != null) {
      if (block.miner == miner || miner == "*") {
        console.log("Found block " + block.number);
        printBlock(block);
      }
      if (block.uncles != null) {
        for (var j = 0; j < 2; j++) {
          var uncle = eth.getUncle(i, j);
          if (uncle != null) {
            if (uncle.miner == miner || miner == "*") {
              console.log("Found uncle " + block.number + " uncle " + j);
              printUncle(block, j, uncle);
            }
          }          
        }
      }
    }
  }
}

getMyMinedBlocks(startBlockNumber, endBlockNumber)

function getMyMinedBlocks(startBlockNumber, endBlockNumber) {
  getMinedBlocks(eth.accounts[0], startBlockNumber, endBlockNumber);
}

Beispiele für die Verwendung der obigen Funktion

Hier sind einige Beispiele für die Verwendung der oben genannten Funktionen im öffentlichen Mainnet-Ethereum-Netzwerk.

  • Druckblock abgebaut von "0x52bc44d5378309ee2abf1539bf71de1b7d7be3b5". Siehe https://etherscan.io/block/1325630

    getMinedBlocks("0x52bc44d5378309ee2abf1539bf71de1b7d7be3b5", 1325620, 1325640);
    
  • Druckblock mit Onkeln, die von "0xf3b9d2c81f2b24b0fa0acaaa865b7d9ced5fc2fb" abgebaut wurden. Siehe https://etherscan.io/block/1325635

    getMinedBlocks("0xf3b9d2c81f2b24b0fa0acaaa865b7d9ced5fc2fb", 1325630, 1325640);
    

    mit der Ausgabe:

    > getMinedBlocks("0xf3b9d2c81f2b24b0fa0acaaa865b7d9ced5fc2fb", 1325630, 1325640);
    Searching for miner "0xf3b9d2c81f2b24b0fa0acaaa865b7d9ced5fc2fb" within blocks 1325630 and 1325640"
    Found uncle 1325635 uncle 0
    Block number     : 1325635 , uncle position: 0
     Uncle number    : 1325634
     hash            : 0xae03bb2d5f1fbde4e22bf79850307ab6ae7d8545a9f0de4a5f529095546308c0
     parentHash      : 0x771b46e0310666780a55b1d603648d89e7d8cc3feac20a175117b4cb7e206a75
     nonce           : 0xeff5922de2f569e8
     sha3Uncles      : 0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347
     logsBloom       : 0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
     transactionsRoot: 0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421
     stateRoot       : 0xafca80bc836c00c7eeb4b6f3254573f72d38a0738ce4793da7d5222ed6c0c5cd
     miner           : 0xf3b9d2c81f2b24b0fa0acaaa865b7d9ced5fc2fb
     difficulty      : 26564802678158
     totalDifficulty : 0
     extraData       : 0x426974436c756220455448204d696e696e6720506f6f6c
     size            : 0
     gasLimit        : 4712388
     gasUsed         : 0
     timestamp       : 1460501836
     transactions    : undefined
    
  • Druckblock mit Onkeln. Siehe https://etherscan.io/block/907703

    getMinedBlocks("*", 907703, 907703);
    
  • Drucken Sie Blöcke, die mein Miner zwischen den Blöcken 1321603 und 1321605 abgebaut hat

    getMyMinedBlocks(1321603, 1321605);
    
printTransactionfunktioniert für mich, gibt aber printBlocknur undefiniert für jeden Parameter zurück. Block number undefined, hash undefined, parentHash undefinedetc. Nennst du es einfach so printBlock("17020")?
printBlock(...)muss angerufen werden getMinedBlocks(...). Oder Sie können verwendenprintBlock(eth.getBlock(17020))

SCHNELLE Möglichkeit, Blöcke auf Transaktionen auf einem Konto zu scannen

Sehen Sie sich den Node.JS-Quellcode oder seine Beispielausgabe an .

Dies ist ein asynchroner Scanner, der 200 Threads zum Scannen erstellt, um nach allen Transaktionen zu suchen, die sich auf Ihre Kontonummer beziehen.

Sie können leicht ändern, was passiert, wenn Ihre Transaktion gefunden wird. Derzeit wird sie nur auf der Konsole gedruckt, damit Sie diese sehen können.

Einige der obigen Antworten zeigten eine synchrone Möglichkeit, alle Blöcke nach Transaktionen zu scannen, aber das synchrone Scannen ist langsam, insbesondere wenn Sie sich über das Internet mit Geth verbinden. Diese Lösung scannt eine große Anzahl von Blöcken schneller.

Laut den Notizen unter dem obigen Link erhalten Sie ungefähr 266 Blöcke pro Sekunde (4.297 Blöcke in 16,111 Sekunden). Ich habe einige Tests durchgeführt, um die Parität (im Gegensatz zu Geth) mit einem Single-Thread-C++-Programm zu erreichen, und ich habe ziemlich konstant etwa 150-180 Blöcke pro Sekunde erhalten. Es gibt also eine Beschleunigung, aber nicht so viel, wie ich gedacht hätte. Es fühlt sich an, als ob Sie die Grenze der Fähigkeit von Geth erreicht haben, Blöcke über RPC zu liefern. Ist das sinnvoll? Haben Sie die verschiedenen Beschleunigungen bei unterschiedlicher Anzahl von Threads getestet?
Ich habe nicht viel getestet, um die Anzahl der Threads zu ändern, außer zu sagen, dass zu viele Threads meine CPU verbrauchen und tatsächlich schlimmer sind als nicht zu viele Threads. Ich habe auch keinen Versuch unternommen, Geth auf eine optimale Vernetzung abzustimmen, was möglicherweise möglich ist, um die Geschwindigkeit weiter zu erhöhen. Ich habe ein Stock-Geth mit Standardeinstellungen verwendet.

Übertragen Sie das GESAMTE Guthaben von einem Konto auf ein anderes

/**
 * Transfer the ENTIRE BALANCE from one account to another.
 *
 * Before you call this, you must unlock your account:
 *   personal.unlockAccount(from)
 *
 * @see https://github.com/ethereum/go-ethereum/issues/1637
 * @see https://github.com/ethereum/go-ethereum/issues/2173
 */
function transferEntireBalance(from, to) {
    var gas = new BigNumber(21000);
    var price = web3.eth.gasPrice;  // current average price; or set your own
    var balance = eth.getBalance(from);
    var value = balance.minus(gas.times(price));
    if (value.greaterThan(0)) {
        var txn = eth.sendTransaction({from: from, to: to, gasPrice: price, gas: gas, value: value});
        console.log("  Transfer", from, "to", to, ":", txn);
        return txn;
    }
    console.log("  Transfer "+ from +" to "+ to +": (No funds available)");
    return null;
}

https://gist.github.com/ross-p/cfa489bb7ed7427e4498058b0d6a5984

Dieser berechnet die für die Transaktion erforderliche Gasmenge und überweist dann 100 % des Geldes (nach den Gaskosten) vom fromKonto auf das toKonto.

Nach Ausführung dieser Methode fromverbleiben auf dem Konto 0 Ether.

Verwendungszweck:

var txn = transferEntireBalance(from, to);
eth.getTransaction(txn);

Am 19. Juli 2017 aktualisiert, um standardmäßig ausschließlich BigNumber-Mathematik und den systemweiten durchschnittlichen gasPrice zu verwenden.

Während dies die Frage theoretisch beantworten kann, wäre es vorzuziehen , die wesentlichen Teile der Antwort hier aufzunehmen und den Link als Referenz bereitzustellen. Es sind nur 20 Codezeilen, fügen Sie sie einfach auch hier ein.

Skript zum Abrufen von Kontoständen und einschließlich TheDAO-Tokens

Hier ist eine Version davon checkAllBalances, die auch TheDAO- Token anzeigt. Es gibt ein Linux-Skript, das Sie über die Befehlszeile unter How do I print my account balances and TheDAO tokens from geth ausführen können .

function padTokens(s, n) {
  var o = s.toPrecision(n);
  while (o.length < n) {
    o = " " + o;
  }
  return o;
}

function padEthers(s) {
  var o = s.toFixed(18);
  while (o.length < 27) {
    o = " " + o;
  }
  return o;
}

function checkAllBalances() { 
  var theDAOABI = [ { "type": "function", "outputs": [ { "type": "uint256", "name": "", "value": "5e+22" } ], "name": "minTokensToCreate", "inputs": [], "constant": true }, { "type": "function", "outputs": [ { "type": "uint256", "name": "", "value": "2.668900014413644230605979e+24" } ], "name": "totalSupply", "inputs": [], "constant": true }, { "type": "function", "outputs": [ { "type": "uint256", "name": "", "value": "1464426000" } ], "name": "closingTime", "inputs": [], "constant": true }, { "type": "function", "outputs": [], "name": "refund", "inputs": [], "constant": false }, { "type": "function", "outputs": [ { "type": "address", "name": "", "value": "0xda4a4626d3e16e094de3225a751aab7128e96526" } ], "name": "curator", "inputs": [], "constant": true }, { "type": "function", "outputs": [ { "type": "uint256", "name": "balance", "value": "0" } ], "name": "balanceOf", "inputs": [ { "type": "address", "name": "_owner" } ], "constant": true }, { "type": "function", "outputs": [ { "type": "uint256", "name": "_numberOfProposals", "value": "0" } ], "name": "numberOfProposals", "inputs": [], "constant": true }, { "type": "function", "outputs": [ { "type": "address", "name": "", "value": "0x807640a13483f8ac783c557fcdf27be11ea4ac7a" } ], "name": "extraBalance", "inputs": [], "constant": true }, { "type": "function", "outputs": [ { "type": "bool", "name": "", "value": true } ], "name": "isFueled", "inputs": [], "constant": true }, { "type": "function", "outputs": [ { "type": "bool", "name": "success" } ], "name": "createTokenProxy", "inputs": [ { "type": "address", "name": "_tokenHolder" } ], "constant": false }, { "type": "function", "outputs": [ { "type": "uint256", "name": "_voteID" } ], "name": "vote", "inputs": [ { "type": "uint256", "name": "_proposalID" }, { "type": "bool", "name": "_supportsProposal" } ], "constant": false }, { "type": "event", "name": "FuelingToDate", "inputs": [ { "type": "uint256", "name": "value", "indexed": false } ], "anonymous": false }, { "type": "event", "name": "ProposalAdded", "inputs": [ { "type": "uint256", "name": "proposalID", "indexed": true }, { "type": "address", "name": "recipient", "indexed": false }, { "type": "uint256", "name": "amount", "indexed": false }, { "type": "bool", "name": "newCurator", "indexed": false }, { "type": "string", "name": "description", "indexed": false } ], "anonymous": false }, { "type": "event", "name": "ProposalTallied", "inputs": [ { "type": "uint256", "name": "proposalID", "indexed": true }, { "type": "bool", "name": "result", "indexed": false }, { "type": "uint256", "name": "quorum", "indexed": false } ], "anonymous": false } ];
  var theDAOAddress = "0xBB9bc244D798123fDe783fCc1C72d3Bb8C189413";
  var theDAO = eth.contract(theDAOABI).at(theDAOAddress);
  var theDAOTotal = 0; 
  var ethersTotal = 0; 

  console.log("  #     Account                                        TheDAO                      ethers");
  console.log("------- ------------------------------------------ ---------- ---------------------------");
  var i =0; 
  eth.accounts.forEach( function(e){
    var tokens = theDAO.balanceOf(e) / parseFloat(1e16);
    theDAOTotal += parseFloat(tokens);
    var ethers = web3.fromWei(eth.getBalance(e), "ether");
    ethersTotal += parseFloat(ethers);
    console.log("  " + i + "\t" + e + " " + padTokens(tokens, 10) + " " + padEthers(ethers)); 
    i++; 
  })
  console.log("------- ------------------------------------------ ---------- ---------------------------");
  console.log("  " + i + "                                               " + padTokens(theDAOTotal, 10) + " " + padEthers(ethersTotal));
}; 

Hier ist eine Beispielausgabe:

> checkAllBalances()
  #     Account                                        TheDAO                      ethers
------- ------------------------------------------ ---------- ---------------------------
  0     0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa       1100        1.111111111111111111
  1     0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb       2200        2.222222222222222222
  2     0xcccccccccccccccccccccccccccccccccccccccc       3300        3.333333333333333333
------- ------------------------------------------ ---------- ---------------------------
  3                                                      6600        6.666666666666666666
Der Link für "TheDAO" ( daohub.org ) ist defekt.

Token in der Blockchain finden, mit freundlicher Genehmigung von https://github.com/linagee/find-ethereum-coins/blob/master/token.js

var tokenInterface = [{"type": "function","name": "name","constant": true,"inputs": [],"outputs": [{"name": "","type": "string"}]},{"type": "function","name": "decimals","constant": true,"inputs": [],"outputs": [{"name": "","type": "uint8"}]},{"type": "function","name": "balanceOf","constant": true,"inputs": [{"name": "","type": "address"}],"outputs": [{"name": "","type": "uint256"}]},{"type": "function","name": "symbol","constant": true,"inputs": [],"outputs": [{"name": "","type": "string"}]},{"type": "function","name": "transfer","constant": false,"inputs": [{"name": "_to","type": "address"},{"name": "_value","type": "uint256"}],"outputs": []},{"type": "constructor","inputs": [{"name": "_supply","type": "uint256"},{"name": "_name","type": "string"},{"name": "_decimals","type": "uint8"},{"name": "_symbol","type": "string"}]},{"name": "Transfer","type": "event","anonymous": false,"inputs": [{"indexed": true,"name": "from","type": "address"},{"indexed": true,"name": "to","type": "address"},{"indexed": false,"name": "value","type": "uint256"}]}];
TokenContract = web3.eth.contract(tokenInterface);

var lowestBlock = 474147; //November 3, 2015 - last time the ABI above was changed
var highestBlock = eth.getBlock("latest").number;
//var lowestBlock = 483325; //smaller test case with just one coin (MistCoin)
//var highestBlock = 484731; //smaller test case with just one coin (MistCoin)
for (var x=lowestBlock; x < highestBlock; x++) {
  var transactions = eth.getBlock(x).transactions;
  for (var y=0; y < transactions.length; y++) {
//    if (x % 100 == 0) { console.log("."); }
    var contractAddr = eth.getTransactionReceipt(transactions[y]).contractAddress;
    if (contractAddr != null) {
       var tokenInstance = TokenContract.at(contractAddr);
       var symbol = "";
       var decimals = "";
       var name = "";
       try {
         symbol = tokenInstance.symbol();
       } catch(err) {
       }
       try {
         decimals = tokenInstance.decimals();
       } catch(err) {
         //don't do anything here, just catch the error so program doesn't die
       }
       try {
         name = tokenInstance.name();
       } catch(err) {
         //don't do anything here, just catch the error so program doesn't die
       }
       if (symbol != null && symbol != "" && name != null && name != "") {
         console.log("-----------");
         console.log("Contract Address: " + contractAddr);
         console.log("Name: " + name);
         console.log("Symbol: " + symbol);
         console.log("Decimals: " + decimals);
         console.log("-----------");
       }
//       console.log(contractAddr);  //testing
    }
  }
//  console.log(eth.getBlock(x).transactions);  //testing
}

So erhalten Sie ganz einfach Ihr Gesamtguthaben:

function totalBalance() { 
  var x = 0
  eth.accounts.forEach( function(e) {
    x = x + parseFloat(web3.fromWei(eth.getBalance(e)), 10); 
  });
  console.log("  total balance: " + x + " ether"); 
};
Hmm ... Ist das nicht fast dasselbe wie das Skript in der Frage?
@varm ist identisch, außer dass es alle Kontostände summiert, anstatt sie einzeln anzuzeigen. Ich hatte tatsächlich das Snippet aus der Frage verwendet und diesen kleinen Zusatz hinzugefügt, um schnell einen Blick auf die Gesamtsumme aller Konten zu werfen.

Eine heuristische Suche nach Geldtransaktionen für ein bestimmtes Konto, ohne die gesamte Kette zu verarbeiten

var myAddr = '0xbb9bc244d798123fde783fcc1c72d3bb8c189413';
var currentBlock = eth.blockNumber;
var n = eth.getTransactionCount(myAddr, currentBlock);
var bal = eth.getBalance(myAddr, currentBlock);
for (var i=currentBlock; i >= 0 && (n > 0 || bal > 0); --i) {
    try {
        var block = eth.getBlock(i, true);
        if (block && block.transactions) {
            block.transactions.forEach(function(e) {
                if (myAddr == e.from) {
                    if (e.from != e.to)
                        bal = bal.plus(e.value);
                    console.log(i, e.from, e.to, e.value.toString(10));
                    --n;
                }
                if (myAddr == e.to) {
                    if (e.from != e.to)
                        bal = bal.minus(e.value);
                    console.log(i, e.from, e.to, e.value.toString(10));
                }
            });
        }
    } catch (e) { console.error("Error in block " + i, e); }
}

Wie funktioniert es?

Unter Verwendung der verfügbaren Informationen über den aktuellen Status (Anzahl der "Von"-Transaktionen und des aktuellen Saldos) geht es in der Zeit zurück, bis mindestens so viele "Von"-Transaktionen gefunden wurden, und geht dann weiter zurück, bis der Saldo erreicht ist 0.

Die inhärente Einschränkung besteht darin, dass Transaktionen mit dem Wert 0 vor der Einzahlung auf das Konto nicht gefunden werden.

Diese Funktion hier überprüft Peers und trennt Handshakes von effektiven Verbindungen:

function getPeers(flagAll) { 
  // always lists established connections
  // if flagAll is true shows handshakes also
  var i =0; 
  var flagHandshake = 0;
  var count00 = 0;
  var count01 = 0;
  var peersHandshake = new Array();
  var peersConnect = new Array();
  admin.peers.forEach( function(e){
    flagHandshake = ( e.protocols.eth == "handshake");
    if (flagHandshake) {
        peersHandshake[count01] = e.network.remoteAddress;
        count01++;
    } else {
        peersConnect[count00] = e.network.remoteAddress;
        count00++;
    }  
  })
  i = 0;
  peersConnect.forEach(function(e){
    console.log("  peersConnect["+i+"] :  [" +  e + "]" ); 
    i++; 
  })
  if (count00 == 0) {
    console.log("  No TRUE connections yet.  Try using `admin.addPeer()` to speed things up.");
  }  else {
    console.log("  Found ["+count00+"] TRUE connections.");
  } 
    
  
  if (flagAll) {
    i = 0;
    peersHandshake.forEach(function(e){
        console.log("  peersHandshake["+i+"] :  [" +  e + "]" ); 
        i++; 
    })
  }
    
};

Nur zum Spaß. Ruft alle Blöcke rekursiv ab :) (nicht der beste Weg)

 function getAllBlocks(blockNumber,res) { 
  if(blockNumber < 0) return; 
  var block = eth.getBlock(blockNumber); 
  res.push(getAllBlocks(block.number-1,res));
  return res; 
 }

getAllBlocks('latest',[])