repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
|---|---|---|---|---|---|---|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/crypto/jce/ECSignatureFactory.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.crypto.jce;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
import java.security.Signature;
public final class ECSignatureFactory {
public static final String RAW_ALGORITHM = "NONEwithECDSA";
private static final String rawAlgorithmAssertionMsg =
"Assumed the JRE supports NONEwithECDSA signatures";
private ECSignatureFactory() { }
public static Signature getRawInstance() {
try {
return Signature.getInstance(RAW_ALGORITHM);
} catch (NoSuchAlgorithmException ex) {
throw new AssertionError(rawAlgorithmAssertionMsg, ex);
}
}
public static Signature getRawInstance(final String provider) throws NoSuchProviderException {
try {
return Signature.getInstance(RAW_ALGORITHM, provider);
} catch (NoSuchAlgorithmException ex) {
throw new AssertionError(rawAlgorithmAssertionMsg, ex);
}
}
public static Signature getRawInstance(final Provider provider) {
try {
return Signature.getInstance(RAW_ALGORITHM, provider);
} catch (NoSuchAlgorithmException ex) {
throw new AssertionError(rawAlgorithmAssertionMsg, ex);
}
}
}
| 2,003
| 33.551724
| 96
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/crypto/jce/ECKeyAgreement.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.crypto.jce;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
import javax.crypto.KeyAgreement;
public final class ECKeyAgreement {
public static final String ALGORITHM = "ECDH";
private static final String algorithmAssertionMsg =
"Assumed the JRE supports EC key agreement";
private ECKeyAgreement() { }
public static KeyAgreement getInstance() {
try {
return KeyAgreement.getInstance(ALGORITHM);
} catch (NoSuchAlgorithmException ex) {
throw new AssertionError(algorithmAssertionMsg, ex);
}
}
public static KeyAgreement getInstance(final String provider) throws NoSuchProviderException {
try {
return KeyAgreement.getInstance(ALGORITHM, provider);
} catch (NoSuchAlgorithmException ex) {
throw new AssertionError(algorithmAssertionMsg, ex);
}
}
public static KeyAgreement getInstance(final Provider provider) {
try {
return KeyAgreement.getInstance(ALGORITHM, provider);
} catch (NoSuchAlgorithmException ex) {
throw new AssertionError(algorithmAssertionMsg, ex);
}
}
}
| 1,962
| 32.271186
| 96
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/crypto/jce/SpongyCastleProvider.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.crypto.jce;
import org.spongycastle.jcajce.provider.config.ConfigurableProvider;
import org.spongycastle.jce.provider.BouncyCastleProvider;
import java.security.Provider;
import java.security.Security;
public final class SpongyCastleProvider {
private static class Holder {
private static final Provider INSTANCE;
static{
Provider p = Security.getProvider("SC");
INSTANCE = (p != null) ? p : new BouncyCastleProvider();
INSTANCE.put("MessageDigest.ETH-KECCAK-256", "org.ethereum.crypto.cryptohash.Keccak256");
INSTANCE.put("MessageDigest.ETH-KECCAK-512", "org.ethereum.crypto.cryptohash.Keccak512");
}
}
public static Provider getInstance() {
return Holder.INSTANCE;
}
}
| 1,565
| 34.590909
| 97
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/crypto/jce/ECKeyFactory.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.crypto.jce;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
public final class ECKeyFactory {
public static final String ALGORITHM = "EC";
private static final String algorithmAssertionMsg =
"Assumed the JRE supports EC key factories";
private ECKeyFactory() { }
private static class Holder {
private static final KeyFactory INSTANCE;
static {
try {
INSTANCE = KeyFactory.getInstance(ALGORITHM);
} catch (NoSuchAlgorithmException ex) {
throw new AssertionError(algorithmAssertionMsg, ex);
}
}
}
public static KeyFactory getInstance() {
return Holder.INSTANCE;
}
public static KeyFactory getInstance(final String provider) throws NoSuchProviderException {
try {
return KeyFactory.getInstance(ALGORITHM, provider);
} catch (NoSuchAlgorithmException ex) {
throw new AssertionError(algorithmAssertionMsg, ex);
}
}
public static KeyFactory getInstance(final Provider provider) {
try {
return KeyFactory.getInstance(ALGORITHM, provider);
} catch (NoSuchAlgorithmException ex) {
throw new AssertionError(algorithmAssertionMsg, ex);
}
}
}
| 2,087
| 30.636364
| 94
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/crypto/jce/ECAlgorithmParameters.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.crypto.jce;
import java.io.IOException;
import java.security.AlgorithmParameters;
import java.security.NoSuchAlgorithmException;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.ECParameterSpec;
import java.security.spec.InvalidParameterSpecException;
public final class ECAlgorithmParameters {
public static final String ALGORITHM = "EC";
public static final String CURVE_NAME = "secp256k1";
private ECAlgorithmParameters() { }
private static class Holder {
private static final AlgorithmParameters INSTANCE;
private static final ECGenParameterSpec SECP256K1_CURVE
= new ECGenParameterSpec(CURVE_NAME);
static {
try {
INSTANCE = AlgorithmParameters.getInstance(ALGORITHM);
INSTANCE.init(SECP256K1_CURVE);
} catch (NoSuchAlgorithmException ex) {
throw new AssertionError(
"Assumed the JRE supports EC algorithm params", ex);
} catch (InvalidParameterSpecException ex) {
throw new AssertionError(
"Assumed correct key spec statically", ex);
}
}
}
public static ECParameterSpec getParameterSpec() {
try {
return Holder.INSTANCE.getParameterSpec(ECParameterSpec.class);
} catch (InvalidParameterSpecException ex) {
throw new AssertionError(
"Assumed correct key spec statically", ex);
}
}
public static byte[] getASN1Encoding() {
try {
return Holder.INSTANCE.getEncoded();
} catch (IOException ex) {
throw new AssertionError(
"Assumed algo params has been initialized", ex);
}
}
}
| 2,413
| 31.621622
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/crypto/cryptohash/KeccakCore.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
// $Id: KeccakCore.java 258 2011-07-15 22:16:50Z tp $
package org.ethereum.crypto.cryptohash;
/**
* This class implements the core operations for the Keccak digest
* algorithm.
*
* <pre>
* ==========================(LICENSE BEGIN)============================
*
* Copyright (c) 2007-2010 Projet RNRT SAPHIR
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* ===========================(LICENSE END)=============================
* </pre>
*
* @version $Revision: 258 $
* @author Thomas Pornin <thomas.pornin@cryptolog.com>
*/
abstract class KeccakCore extends DigestEngine{
KeccakCore(String alg)
{
super(alg);
}
private long[] A;
private byte[] tmpOut;
private static final long[] RC = {
0x0000000000000001L, 0x0000000000008082L,
0x800000000000808AL, 0x8000000080008000L,
0x000000000000808BL, 0x0000000080000001L,
0x8000000080008081L, 0x8000000000008009L,
0x000000000000008AL, 0x0000000000000088L,
0x0000000080008009L, 0x000000008000000AL,
0x000000008000808BL, 0x800000000000008BL,
0x8000000000008089L, 0x8000000000008003L,
0x8000000000008002L, 0x8000000000000080L,
0x000000000000800AL, 0x800000008000000AL,
0x8000000080008081L, 0x8000000000008080L,
0x0000000080000001L, 0x8000000080008008L
};
/**
* Encode the 64-bit word {@code val} into the array
* {@code buf} at offset {@code off}, in little-endian
* convention (least significant byte first).
*
* @param val the value to encode
* @param buf the destination buffer
* @param off the destination offset
*/
private static void encodeLELong(long val, byte[] buf, int off)
{
buf[off + 0] = (byte)val;
buf[off + 1] = (byte)(val >>> 8);
buf[off + 2] = (byte)(val >>> 16);
buf[off + 3] = (byte)(val >>> 24);
buf[off + 4] = (byte)(val >>> 32);
buf[off + 5] = (byte)(val >>> 40);
buf[off + 6] = (byte)(val >>> 48);
buf[off + 7] = (byte)(val >>> 56);
}
/**
* Decode a 64-bit little-endian word from the array {@code buf}
* at offset {@code off}.
*
* @param buf the source buffer
* @param off the source offset
* @return the decoded value
*/
private static long decodeLELong(byte[] buf, int off)
{
return (buf[off + 0] & 0xFFL)
| ((buf[off + 1] & 0xFFL) << 8)
| ((buf[off + 2] & 0xFFL) << 16)
| ((buf[off + 3] & 0xFFL) << 24)
| ((buf[off + 4] & 0xFFL) << 32)
| ((buf[off + 5] & 0xFFL) << 40)
| ((buf[off + 6] & 0xFFL) << 48)
| ((buf[off + 7] & 0xFFL) << 56);
}
/** @see org.ethereum.crypto.cryptohash.DigestEngine */
protected void engineReset()
{
doReset();
}
/** @see org.ethereum.crypto.cryptohash.DigestEngine */
protected void processBlock(byte[] data)
{
/* Input block */
for (int i = 0; i < data.length; i += 8)
A[i >>> 3] ^= decodeLELong(data, i);
long t0, t1, t2, t3, t4;
long tt0, tt1, tt2, tt3, tt4;
long t, kt;
long c0, c1, c2, c3, c4, bnn;
/*
* Unrolling four rounds kills performance big time
* on Intel x86 Core2, in both 32-bit and 64-bit modes
* (less than 1 MB/s instead of 55 MB/s on x86-64).
* Unrolling two rounds appears to be fine.
*/
for (int j = 0; j < 24; j += 2) {
tt0 = A[ 1] ^ A[ 6];
tt1 = A[11] ^ A[16];
tt0 ^= A[21] ^ tt1;
tt0 = (tt0 << 1) | (tt0 >>> 63);
tt2 = A[ 4] ^ A[ 9];
tt3 = A[14] ^ A[19];
tt0 ^= A[24];
tt2 ^= tt3;
t0 = tt0 ^ tt2;
tt0 = A[ 2] ^ A[ 7];
tt1 = A[12] ^ A[17];
tt0 ^= A[22] ^ tt1;
tt0 = (tt0 << 1) | (tt0 >>> 63);
tt2 = A[ 0] ^ A[ 5];
tt3 = A[10] ^ A[15];
tt0 ^= A[20];
tt2 ^= tt3;
t1 = tt0 ^ tt2;
tt0 = A[ 3] ^ A[ 8];
tt1 = A[13] ^ A[18];
tt0 ^= A[23] ^ tt1;
tt0 = (tt0 << 1) | (tt0 >>> 63);
tt2 = A[ 1] ^ A[ 6];
tt3 = A[11] ^ A[16];
tt0 ^= A[21];
tt2 ^= tt3;
t2 = tt0 ^ tt2;
tt0 = A[ 4] ^ A[ 9];
tt1 = A[14] ^ A[19];
tt0 ^= A[24] ^ tt1;
tt0 = (tt0 << 1) | (tt0 >>> 63);
tt2 = A[ 2] ^ A[ 7];
tt3 = A[12] ^ A[17];
tt0 ^= A[22];
tt2 ^= tt3;
t3 = tt0 ^ tt2;
tt0 = A[ 0] ^ A[ 5];
tt1 = A[10] ^ A[15];
tt0 ^= A[20] ^ tt1;
tt0 = (tt0 << 1) | (tt0 >>> 63);
tt2 = A[ 3] ^ A[ 8];
tt3 = A[13] ^ A[18];
tt0 ^= A[23];
tt2 ^= tt3;
t4 = tt0 ^ tt2;
A[ 0] = A[ 0] ^ t0;
A[ 5] = A[ 5] ^ t0;
A[10] = A[10] ^ t0;
A[15] = A[15] ^ t0;
A[20] = A[20] ^ t0;
A[ 1] = A[ 1] ^ t1;
A[ 6] = A[ 6] ^ t1;
A[11] = A[11] ^ t1;
A[16] = A[16] ^ t1;
A[21] = A[21] ^ t1;
A[ 2] = A[ 2] ^ t2;
A[ 7] = A[ 7] ^ t2;
A[12] = A[12] ^ t2;
A[17] = A[17] ^ t2;
A[22] = A[22] ^ t2;
A[ 3] = A[ 3] ^ t3;
A[ 8] = A[ 8] ^ t3;
A[13] = A[13] ^ t3;
A[18] = A[18] ^ t3;
A[23] = A[23] ^ t3;
A[ 4] = A[ 4] ^ t4;
A[ 9] = A[ 9] ^ t4;
A[14] = A[14] ^ t4;
A[19] = A[19] ^ t4;
A[24] = A[24] ^ t4;
A[ 5] = (A[ 5] << 36) | (A[ 5] >>> (64 - 36));
A[10] = (A[10] << 3) | (A[10] >>> (64 - 3));
A[15] = (A[15] << 41) | (A[15] >>> (64 - 41));
A[20] = (A[20] << 18) | (A[20] >>> (64 - 18));
A[ 1] = (A[ 1] << 1) | (A[ 1] >>> (64 - 1));
A[ 6] = (A[ 6] << 44) | (A[ 6] >>> (64 - 44));
A[11] = (A[11] << 10) | (A[11] >>> (64 - 10));
A[16] = (A[16] << 45) | (A[16] >>> (64 - 45));
A[21] = (A[21] << 2) | (A[21] >>> (64 - 2));
A[ 2] = (A[ 2] << 62) | (A[ 2] >>> (64 - 62));
A[ 7] = (A[ 7] << 6) | (A[ 7] >>> (64 - 6));
A[12] = (A[12] << 43) | (A[12] >>> (64 - 43));
A[17] = (A[17] << 15) | (A[17] >>> (64 - 15));
A[22] = (A[22] << 61) | (A[22] >>> (64 - 61));
A[ 3] = (A[ 3] << 28) | (A[ 3] >>> (64 - 28));
A[ 8] = (A[ 8] << 55) | (A[ 8] >>> (64 - 55));
A[13] = (A[13] << 25) | (A[13] >>> (64 - 25));
A[18] = (A[18] << 21) | (A[18] >>> (64 - 21));
A[23] = (A[23] << 56) | (A[23] >>> (64 - 56));
A[ 4] = (A[ 4] << 27) | (A[ 4] >>> (64 - 27));
A[ 9] = (A[ 9] << 20) | (A[ 9] >>> (64 - 20));
A[14] = (A[14] << 39) | (A[14] >>> (64 - 39));
A[19] = (A[19] << 8) | (A[19] >>> (64 - 8));
A[24] = (A[24] << 14) | (A[24] >>> (64 - 14));
bnn = ~A[12];
kt = A[ 6] | A[12];
c0 = A[ 0] ^ kt;
kt = bnn | A[18];
c1 = A[ 6] ^ kt;
kt = A[18] & A[24];
c2 = A[12] ^ kt;
kt = A[24] | A[ 0];
c3 = A[18] ^ kt;
kt = A[ 0] & A[ 6];
c4 = A[24] ^ kt;
A[ 0] = c0;
A[ 6] = c1;
A[12] = c2;
A[18] = c3;
A[24] = c4;
bnn = ~A[22];
kt = A[ 9] | A[10];
c0 = A[ 3] ^ kt;
kt = A[10] & A[16];
c1 = A[ 9] ^ kt;
kt = A[16] | bnn;
c2 = A[10] ^ kt;
kt = A[22] | A[ 3];
c3 = A[16] ^ kt;
kt = A[ 3] & A[ 9];
c4 = A[22] ^ kt;
A[ 3] = c0;
A[ 9] = c1;
A[10] = c2;
A[16] = c3;
A[22] = c4;
bnn = ~A[19];
kt = A[ 7] | A[13];
c0 = A[ 1] ^ kt;
kt = A[13] & A[19];
c1 = A[ 7] ^ kt;
kt = bnn & A[20];
c2 = A[13] ^ kt;
kt = A[20] | A[ 1];
c3 = bnn ^ kt;
kt = A[ 1] & A[ 7];
c4 = A[20] ^ kt;
A[ 1] = c0;
A[ 7] = c1;
A[13] = c2;
A[19] = c3;
A[20] = c4;
bnn = ~A[17];
kt = A[ 5] & A[11];
c0 = A[ 4] ^ kt;
kt = A[11] | A[17];
c1 = A[ 5] ^ kt;
kt = bnn | A[23];
c2 = A[11] ^ kt;
kt = A[23] & A[ 4];
c3 = bnn ^ kt;
kt = A[ 4] | A[ 5];
c4 = A[23] ^ kt;
A[ 4] = c0;
A[ 5] = c1;
A[11] = c2;
A[17] = c3;
A[23] = c4;
bnn = ~A[ 8];
kt = bnn & A[14];
c0 = A[ 2] ^ kt;
kt = A[14] | A[15];
c1 = bnn ^ kt;
kt = A[15] & A[21];
c2 = A[14] ^ kt;
kt = A[21] | A[ 2];
c3 = A[15] ^ kt;
kt = A[ 2] & A[ 8];
c4 = A[21] ^ kt;
A[ 2] = c0;
A[ 8] = c1;
A[14] = c2;
A[15] = c3;
A[21] = c4;
A[ 0] = A[ 0] ^ RC[j + 0];
tt0 = A[ 6] ^ A[ 9];
tt1 = A[ 7] ^ A[ 5];
tt0 ^= A[ 8] ^ tt1;
tt0 = (tt0 << 1) | (tt0 >>> 63);
tt2 = A[24] ^ A[22];
tt3 = A[20] ^ A[23];
tt0 ^= A[21];
tt2 ^= tt3;
t0 = tt0 ^ tt2;
tt0 = A[12] ^ A[10];
tt1 = A[13] ^ A[11];
tt0 ^= A[14] ^ tt1;
tt0 = (tt0 << 1) | (tt0 >>> 63);
tt2 = A[ 0] ^ A[ 3];
tt3 = A[ 1] ^ A[ 4];
tt0 ^= A[ 2];
tt2 ^= tt3;
t1 = tt0 ^ tt2;
tt0 = A[18] ^ A[16];
tt1 = A[19] ^ A[17];
tt0 ^= A[15] ^ tt1;
tt0 = (tt0 << 1) | (tt0 >>> 63);
tt2 = A[ 6] ^ A[ 9];
tt3 = A[ 7] ^ A[ 5];
tt0 ^= A[ 8];
tt2 ^= tt3;
t2 = tt0 ^ tt2;
tt0 = A[24] ^ A[22];
tt1 = A[20] ^ A[23];
tt0 ^= A[21] ^ tt1;
tt0 = (tt0 << 1) | (tt0 >>> 63);
tt2 = A[12] ^ A[10];
tt3 = A[13] ^ A[11];
tt0 ^= A[14];
tt2 ^= tt3;
t3 = tt0 ^ tt2;
tt0 = A[ 0] ^ A[ 3];
tt1 = A[ 1] ^ A[ 4];
tt0 ^= A[ 2] ^ tt1;
tt0 = (tt0 << 1) | (tt0 >>> 63);
tt2 = A[18] ^ A[16];
tt3 = A[19] ^ A[17];
tt0 ^= A[15];
tt2 ^= tt3;
t4 = tt0 ^ tt2;
A[ 0] = A[ 0] ^ t0;
A[ 3] = A[ 3] ^ t0;
A[ 1] = A[ 1] ^ t0;
A[ 4] = A[ 4] ^ t0;
A[ 2] = A[ 2] ^ t0;
A[ 6] = A[ 6] ^ t1;
A[ 9] = A[ 9] ^ t1;
A[ 7] = A[ 7] ^ t1;
A[ 5] = A[ 5] ^ t1;
A[ 8] = A[ 8] ^ t1;
A[12] = A[12] ^ t2;
A[10] = A[10] ^ t2;
A[13] = A[13] ^ t2;
A[11] = A[11] ^ t2;
A[14] = A[14] ^ t2;
A[18] = A[18] ^ t3;
A[16] = A[16] ^ t3;
A[19] = A[19] ^ t3;
A[17] = A[17] ^ t3;
A[15] = A[15] ^ t3;
A[24] = A[24] ^ t4;
A[22] = A[22] ^ t4;
A[20] = A[20] ^ t4;
A[23] = A[23] ^ t4;
A[21] = A[21] ^ t4;
A[ 3] = (A[ 3] << 36) | (A[ 3] >>> (64 - 36));
A[ 1] = (A[ 1] << 3) | (A[ 1] >>> (64 - 3));
A[ 4] = (A[ 4] << 41) | (A[ 4] >>> (64 - 41));
A[ 2] = (A[ 2] << 18) | (A[ 2] >>> (64 - 18));
A[ 6] = (A[ 6] << 1) | (A[ 6] >>> (64 - 1));
A[ 9] = (A[ 9] << 44) | (A[ 9] >>> (64 - 44));
A[ 7] = (A[ 7] << 10) | (A[ 7] >>> (64 - 10));
A[ 5] = (A[ 5] << 45) | (A[ 5] >>> (64 - 45));
A[ 8] = (A[ 8] << 2) | (A[ 8] >>> (64 - 2));
A[12] = (A[12] << 62) | (A[12] >>> (64 - 62));
A[10] = (A[10] << 6) | (A[10] >>> (64 - 6));
A[13] = (A[13] << 43) | (A[13] >>> (64 - 43));
A[11] = (A[11] << 15) | (A[11] >>> (64 - 15));
A[14] = (A[14] << 61) | (A[14] >>> (64 - 61));
A[18] = (A[18] << 28) | (A[18] >>> (64 - 28));
A[16] = (A[16] << 55) | (A[16] >>> (64 - 55));
A[19] = (A[19] << 25) | (A[19] >>> (64 - 25));
A[17] = (A[17] << 21) | (A[17] >>> (64 - 21));
A[15] = (A[15] << 56) | (A[15] >>> (64 - 56));
A[24] = (A[24] << 27) | (A[24] >>> (64 - 27));
A[22] = (A[22] << 20) | (A[22] >>> (64 - 20));
A[20] = (A[20] << 39) | (A[20] >>> (64 - 39));
A[23] = (A[23] << 8) | (A[23] >>> (64 - 8));
A[21] = (A[21] << 14) | (A[21] >>> (64 - 14));
bnn = ~A[13];
kt = A[ 9] | A[13];
c0 = A[ 0] ^ kt;
kt = bnn | A[17];
c1 = A[ 9] ^ kt;
kt = A[17] & A[21];
c2 = A[13] ^ kt;
kt = A[21] | A[ 0];
c3 = A[17] ^ kt;
kt = A[ 0] & A[ 9];
c4 = A[21] ^ kt;
A[ 0] = c0;
A[ 9] = c1;
A[13] = c2;
A[17] = c3;
A[21] = c4;
bnn = ~A[14];
kt = A[22] | A[ 1];
c0 = A[18] ^ kt;
kt = A[ 1] & A[ 5];
c1 = A[22] ^ kt;
kt = A[ 5] | bnn;
c2 = A[ 1] ^ kt;
kt = A[14] | A[18];
c3 = A[ 5] ^ kt;
kt = A[18] & A[22];
c4 = A[14] ^ kt;
A[18] = c0;
A[22] = c1;
A[ 1] = c2;
A[ 5] = c3;
A[14] = c4;
bnn = ~A[23];
kt = A[10] | A[19];
c0 = A[ 6] ^ kt;
kt = A[19] & A[23];
c1 = A[10] ^ kt;
kt = bnn & A[ 2];
c2 = A[19] ^ kt;
kt = A[ 2] | A[ 6];
c3 = bnn ^ kt;
kt = A[ 6] & A[10];
c4 = A[ 2] ^ kt;
A[ 6] = c0;
A[10] = c1;
A[19] = c2;
A[23] = c3;
A[ 2] = c4;
bnn = ~A[11];
kt = A[ 3] & A[ 7];
c0 = A[24] ^ kt;
kt = A[ 7] | A[11];
c1 = A[ 3] ^ kt;
kt = bnn | A[15];
c2 = A[ 7] ^ kt;
kt = A[15] & A[24];
c3 = bnn ^ kt;
kt = A[24] | A[ 3];
c4 = A[15] ^ kt;
A[24] = c0;
A[ 3] = c1;
A[ 7] = c2;
A[11] = c3;
A[15] = c4;
bnn = ~A[16];
kt = bnn & A[20];
c0 = A[12] ^ kt;
kt = A[20] | A[ 4];
c1 = bnn ^ kt;
kt = A[ 4] & A[ 8];
c2 = A[20] ^ kt;
kt = A[ 8] | A[12];
c3 = A[ 4] ^ kt;
kt = A[12] & A[16];
c4 = A[ 8] ^ kt;
A[12] = c0;
A[16] = c1;
A[20] = c2;
A[ 4] = c3;
A[ 8] = c4;
A[ 0] = A[ 0] ^ RC[j + 1];
t = A[ 5];
A[ 5] = A[18];
A[18] = A[11];
A[11] = A[10];
A[10] = A[ 6];
A[ 6] = A[22];
A[22] = A[20];
A[20] = A[12];
A[12] = A[19];
A[19] = A[15];
A[15] = A[24];
A[24] = A[ 8];
A[ 8] = t;
t = A[ 1];
A[ 1] = A[ 9];
A[ 9] = A[14];
A[14] = A[ 2];
A[ 2] = A[13];
A[13] = A[23];
A[23] = A[ 4];
A[ 4] = A[21];
A[21] = A[16];
A[16] = A[ 3];
A[ 3] = A[17];
A[17] = A[ 7];
A[ 7] = t;
}
}
/** @see org.ethereum.crypto.cryptohash.DigestEngine */
protected void doPadding(byte[] out, int off)
{
int ptr = flush();
byte[] buf = getBlockBuffer();
if ((ptr + 1) == buf.length) {
buf[ptr] = (byte)0x81;
} else {
buf[ptr] = (byte)0x01;
for (int i = ptr + 1; i < (buf.length - 1); i ++)
buf[i] = 0;
buf[buf.length - 1] = (byte)0x80;
}
processBlock(buf);
A[ 1] = ~A[ 1];
A[ 2] = ~A[ 2];
A[ 8] = ~A[ 8];
A[12] = ~A[12];
A[17] = ~A[17];
A[20] = ~A[20];
int dlen = engineGetDigestLength();
for (int i = 0; i < dlen; i += 8)
encodeLELong(A[i >>> 3], tmpOut, i);
System.arraycopy(tmpOut, 0, out, off, dlen);
}
/** @see org.ethereum.crypto.cryptohash.DigestEngine */
protected void doInit()
{
A = new long[25];
tmpOut = new byte[(engineGetDigestLength() + 7) & ~7];
doReset();
}
/** @see org.ethereum.crypto.cryptohash.Digest */
public int getBlockLength()
{
return 200 - 2 * engineGetDigestLength();
}
private final void doReset()
{
for (int i = 0; i < 25; i ++)
A[i] = 0;
A[ 1] = 0xFFFFFFFFFFFFFFFFL;
A[ 2] = 0xFFFFFFFFFFFFFFFFL;
A[ 8] = 0xFFFFFFFFFFFFFFFFL;
A[12] = 0xFFFFFFFFFFFFFFFFL;
A[17] = 0xFFFFFFFFFFFFFFFFL;
A[20] = 0xFFFFFFFFFFFFFFFFL;
}
/** @see org.ethereum.crypto.cryptohash.DigestEngine */
protected Digest copyState(KeccakCore dst)
{
System.arraycopy(A, 0, dst.A, 0, 25);
return super.copyState(dst);
}
/** @see org.ethereum.crypto.cryptohash.Digest */
public String toString()
{
return "Keccak-" + (engineGetDigestLength() << 3);
}
}
| 15,672
| 24.948675
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/crypto/cryptohash/Keccak512.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
// $Id: Keccak512.java 189 2010-05-14 21:21:46Z tp $
package org.ethereum.crypto.cryptohash;
/**
* <p>This class implements the Keccak-256 digest algorithm under the
* {@link Digest} API.</p>
*
* <pre>
* ==========================(LICENSE BEGIN)============================
*
* Copyright (c) 2007-2010 Projet RNRT SAPHIR
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* ===========================(LICENSE END)=============================
* </pre>
*
* @version $Revision: 189 $
* @author Thomas Pornin <thomas.pornin@cryptolog.com>
*/
public class Keccak512 extends KeccakCore {
/**
* Create the engine.
*/
public Keccak512()
{
super("eth-keccak-512");
}
/** @see Digest */
public Digest copy()
{
return copyState(new Keccak512());
}
/** @see Digest */
public int engineGetDigestLength()
{
return 64;
}
@Override
protected byte[] engineDigest() {
return null;
}
@Override
protected void engineUpdate(byte input) {
}
@Override
protected void engineUpdate(byte[] input, int offset, int len) {
}
}
| 2,887
| 30.391304
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/crypto/cryptohash/Keccak256.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
// $Id: Keccak256.java 189 2010-05-14 21:21:46Z tp $
package org.ethereum.crypto.cryptohash;
/**
* <p>This class implements the Keccak-256 digest algorithm under the
* {@link org.ethereum.crypto.cryptohash.Digest} API.</p>
*
* <pre>
* ==========================(LICENSE BEGIN)============================
*
* Copyright (c) 2007-2010 Projet RNRT SAPHIR
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* ===========================(LICENSE END)=============================
* </pre>
*
* @version $Revision: 189 $
* @author Thomas Pornin <thomas.pornin@cryptolog.com>
*/
public class Keccak256 extends KeccakCore {
/**
* Create the engine.
*/
public Keccak256()
{
super("eth-keccak-256");
}
/** @see org.ethereum.crypto.cryptohash.Digest */
public Digest copy()
{
return copyState(new Keccak256());
}
/** @see org.ethereum.crypto.cryptohash.Digest */
public int engineGetDigestLength()
{
return 32;
}
@Override
protected byte[] engineDigest() {
return null;
}
@Override
protected void engineUpdate(byte arg0) {
}
@Override
protected void engineUpdate(byte[] arg0, int arg1, int arg2) {
}
}
| 2,977
| 31.369565
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/crypto/cryptohash/Digest.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
// $Id: Digest.java 232 2010-06-17 14:19:24Z tp $
package org.ethereum.crypto.cryptohash;
/**
* <p>This interface documents the API for a hash function. This
* interface somewhat mimics the standard {@code
* java.security.MessageDigest} class. We do not extend that class in
* order to provide compatibility with reduced Java implementations such
* as J2ME. Implementing a {@code java.security.Provider} compatible
* with Sun's JCA ought to be easy.</p>
*
* <p>A {@code Digest} object maintains a running state for a hash
* function computation. Data is inserted with {@code update()} calls;
* the result is obtained from a {@code digest()} method (where some
* final data can be inserted as well). When a digest output has been
* produced, the objet is automatically resetted, and can be used
* immediately for another digest operation. The state of a computation
* can be cloned with the {@link #copy} method; this can be used to get
* a partial hash result without interrupting the complete
* computation.</p>
*
* <p>{@code Digest} objects are stateful and hence not thread-safe;
* however, distinct {@code Digest} objects can be accessed concurrently
* without any problem.</p>
*
* <pre>
* ==========================(LICENSE BEGIN)============================
*
* Copyright (c) 2007-2010 Projet RNRT SAPHIR
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* ===========================(LICENSE END)=============================
* </pre>
*
* @version $Revision: 232 $
* @author Thomas Pornin <thomas.pornin@cryptolog.com>
*/
public interface Digest{
/**
* Insert one more input data byte.
*
* @param in the input byte
*/
void update(byte in);
/**
* Insert some more bytes.
*
* @param inbuf the data bytes
*/
void update(byte[] inbuf);
/**
* Insert some more bytes.
*
* @param inbuf the data buffer
* @param off the data offset in {@code inbuf}
* @param len the data length (in bytes)
*/
void update(byte[] inbuf, int off, int len);
/**
* Finalize the current hash computation and return the hash value
* in a newly-allocated array. The object is resetted.
*
* @return the hash output
*/
byte[] digest();
/**
* Input some bytes, then finalize the current hash computation
* and return the hash value in a newly-allocated array. The object
* is resetted.
*
* @param inbuf the input data
* @return the hash output
*/
byte[] digest(byte[] inbuf);
/**
* Finalize the current hash computation and store the hash value
* in the provided output buffer. The {@code len} parameter
* contains the maximum number of bytes that should be written;
* no more bytes than the natural hash function output length will
* be produced. If {@code len} is smaller than the natural
* hash output length, the hash output is truncated to its first
* {@code len} bytes. The object is resetted.
*
* @param outbuf the output buffer
* @param off the output offset within {@code outbuf}
* @param len the requested hash output length (in bytes)
* @return the number of bytes actually written in {@code outbuf}
*/
int digest(byte[] outbuf, int off, int len);
/**
* Get the natural hash function output length (in bytes).
*
* @return the digest output length (in bytes)
*/
int getDigestLength();
/**
* Reset the object: this makes it suitable for a new hash
* computation. The current computation, if any, is discarded.
*/
void reset();
/**
* Clone the current state. The returned object evolves independantly
* of this object.
*
* @return the clone
*/
Digest copy();
/**
* <p>Return the "block length" for the hash function. This
* value is naturally defined for iterated hash functions
* (Merkle-Damgard). It is used in HMAC (that's what the
* <a href="http://tools.ietf.org/html/rfc2104">HMAC specification</a>
* names the "{@code B}" parameter).</p>
*
* <p>If the function is "block-less" then this function may
* return {@code -n} where {@code n} is an integer such that the
* block length for HMAC ("{@code B}") will be inferred from the
* key length, by selecting the smallest multiple of {@code n}
* which is no smaller than the key length. For instance, for
* the Fugue-xxx hash functions, this function returns -4: the
* virtual block length B is the HMAC key length, rounded up to
* the next multiple of 4.</p>
*
* @return the internal block length (in bytes), or {@code -n}
*/
int getBlockLength();
/**
* <p>Get the display name for this function (e.g. {@code "SHA-1"}
* for SHA-1).</p>
*
* @see Object
*/
String toString();
}
| 6,489
| 34.464481
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/crypto/cryptohash/DigestEngine.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
// $Id: DigestEngine.java 229 2010-06-16 20:22:27Z tp $
package org.ethereum.crypto.cryptohash;
import java.security.MessageDigest;
/**
* <p>This class is a template which can be used to implement hash
* functions. It takes care of some of the API, and also provides an
* internal data buffer whose length is equal to the hash function
* internal block length.</p>
*
* <p>Classes which use this template MUST provide a working {@link
* #getBlockLength} method even before initialization (alternatively,
* they may define a custom {@link #getInternalBlockLength} which does
* not call {@link #getBlockLength}. The {@link #getDigestLength} should
* also be operational from the beginning, but it is acceptable that it
* returns 0 while the {@link #doInit} method has not been called
* yet.</p>
*
* <pre>
* ==========================(LICENSE BEGIN)============================
*
* Copyright (c) 2007-2010 Projet RNRT SAPHIR
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* ===========================(LICENSE END)=============================
* </pre>
*
* @version $Revision: 229 $
* @author Thomas Pornin <thomas.pornin@cryptolog.com>
*/
public abstract class DigestEngine extends MessageDigest implements Digest {
/**
* Reset the hash algorithm state.
*/
protected abstract void engineReset();
/**
* Process one block of data.
*
* @param data the data block
*/
protected abstract void processBlock(byte[] data);
/**
* Perform the final padding and store the result in the
* provided buffer. This method shall call {@link #flush}
* and then {@link #update} with the appropriate padding
* data in order to get the full input data.
*
* @param buf the output buffer
* @param off the output offset
*/
protected abstract void doPadding(byte[] buf, int off);
/**
* This function is called at object creation time; the
* implementation should use it to perform initialization tasks.
* After this method is called, the implementation should be ready
* to process data or meaningfully honour calls such as
* {@link #engineGetDigestLength}
*/
protected abstract void doInit();
private int digestLen, blockLen, inputLen;
private byte[] inputBuf, outputBuf;
private long blockCount;
/**
* Instantiate the engine.
*/
public DigestEngine(String alg)
{
super(alg);
doInit();
digestLen = engineGetDigestLength();
blockLen = getInternalBlockLength();
inputBuf = new byte[blockLen];
outputBuf = new byte[digestLen];
inputLen = 0;
blockCount = 0;
}
private void adjustDigestLen()
{
if (digestLen == 0) {
digestLen = engineGetDigestLength();
outputBuf = new byte[digestLen];
}
}
/** @see org.ethereum.crypto.cryptohash.Digest */
public byte[] digest()
{
adjustDigestLen();
byte[] result = new byte[digestLen];
digest(result, 0, digestLen);
return result;
}
/** @see org.ethereum.crypto.cryptohash.Digest */
public byte[] digest(byte[] input)
{
update(input, 0, input.length);
return digest();
}
/** @see org.ethereum.crypto.cryptohash.Digest */
public int digest(byte[] buf, int offset, int len)
{
adjustDigestLen();
if (len >= digestLen) {
doPadding(buf, offset);
reset();
return digestLen;
} else {
doPadding(outputBuf, 0);
System.arraycopy(outputBuf, 0, buf, offset, len);
reset();
return len;
}
}
/** @see org.ethereum.crypto.cryptohash.Digest */
public void reset()
{
engineReset();
inputLen = 0;
blockCount = 0;
}
/** @see org.ethereum.crypto.cryptohash.Digest */
public void update(byte input)
{
inputBuf[inputLen ++] = (byte)input;
if (inputLen == blockLen) {
processBlock(inputBuf);
blockCount ++;
inputLen = 0;
}
}
/** @see org.ethereum.crypto.cryptohash.Digest */
public void update(byte[] input)
{
update(input, 0, input.length);
}
/** @see org.ethereum.crypto.cryptohash.Digest */
public void update(byte[] input, int offset, int len)
{
while (len > 0) {
int copyLen = blockLen - inputLen;
if (copyLen > len)
copyLen = len;
System.arraycopy(input, offset, inputBuf, inputLen,
copyLen);
offset += copyLen;
inputLen += copyLen;
len -= copyLen;
if (inputLen == blockLen) {
processBlock(inputBuf);
blockCount ++;
inputLen = 0;
}
}
}
/**
* Get the internal block length. This is the length (in
* bytes) of the array which will be passed as parameter to
* {@link #processBlock}. The default implementation of this
* method calls {@link #getBlockLength} and returns the same
* value. Overriding this method is useful when the advertised
* block length (which is used, for instance, by HMAC) is
* suboptimal with regards to internal buffering needs.
*
* @return the internal block length (in bytes)
*/
protected int getInternalBlockLength()
{
return getBlockLength();
}
/**
* Flush internal buffers, so that less than a block of data
* may at most be upheld.
*
* @return the number of bytes still unprocessed after the flush
*/
protected final int flush()
{
return inputLen;
}
/**
* Get a reference to an internal buffer with the same size
* than a block. The contents of that buffer are defined only
* immediately after a call to {@link #flush()}: if
* {@link #flush()} return the value {@code n}, then the
* first {@code n} bytes of the array returned by this method
* are the {@code n} bytes of input data which are still
* unprocessed. The values of the remaining bytes are
* undefined and may be altered at will.
*
* @return a block-sized internal buffer
*/
protected final byte[] getBlockBuffer()
{
return inputBuf;
}
/**
* Get the "block count": this is the number of times the
* {@link #processBlock} method has been invoked for the
* current hash operation. That counter is incremented
* <em>after</em> the call to {@link #processBlock}.
*
* @return the block count
*/
protected long getBlockCount()
{
return blockCount;
}
/**
* This function copies the internal buffering state to some
* other instance of a class extending {@code DigestEngine}.
* It returns a reference to the copy. This method is intended
* to be called by the implementation of the {@link #copy}
* method.
*
* @param dest the copy
* @return the value {@code dest}
*/
protected Digest copyState(DigestEngine dest)
{
dest.inputLen = inputLen;
dest.blockCount = blockCount;
System.arraycopy(inputBuf, 0, dest.inputBuf, 0,
inputBuf.length);
adjustDigestLen();
dest.adjustDigestLen();
System.arraycopy(outputBuf, 0, dest.outputBuf, 0,
outputBuf.length);
return dest;
}
}
| 8,484
| 28.56446
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/crypto/zksnark/Fp12.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.crypto.zksnark;
import java.math.BigInteger;
/**
* Arithmetic in Fp_12 <br/>
* <br/>
*
* "p" equals 21888242871839275222246405745257275088696311157297823662689037894645226208583, <br/>
* elements of Fp_12 are represented with 2 elements of {@link Fp6} <br/>
* <br/>
*
* Field arithmetic is ported from <a href="https://github.com/scipr-lab/libff/blob/master/libff/algebra/fields/fp12_2over3over2.tcc">libff</a>
*
* @author Mikhail Kalinin
* @since 02.09.2017
*/
class Fp12 implements Field<Fp12> {
static final Fp12 ZERO = new Fp12(Fp6.ZERO, Fp6.ZERO);
static final Fp12 _1 = new Fp12(Fp6._1, Fp6.ZERO);
Fp6 a;
Fp6 b;
Fp12 (Fp6 a, Fp6 b) {
this.a = a;
this.b = b;
}
@Override
public Fp12 squared() {
Fp6 ab = a.mul(b);
Fp6 ra = a.add(b).mul(a.add(b.mulByNonResidue())).sub(ab).sub(ab.mulByNonResidue());
Fp6 rb = ab.add(ab);
return new Fp12(ra, rb);
}
@Override
public Fp12 dbl() {
return null;
}
Fp12 mulBy024(Fp2 ell0, Fp2 ellVW, Fp2 ellVV) {
Fp2 z0 = a.a;
Fp2 z1 = a.b;
Fp2 z2 = a.c;
Fp2 z3 = b.a;
Fp2 z4 = b.b;
Fp2 z5 = b.c;
Fp2 x0 = ell0;
Fp2 x2 = ellVV;
Fp2 x4 = ellVW;
Fp2 t0, t1, t2, s0, t3, t4, d0, d2, d4, s1;
d0 = z0.mul(x0);
d2 = z2.mul(x2);
d4 = z4.mul(x4);
t2 = z0.add(z4);
t1 = z0.add(z2);
s0 = z1.add(z3).add(z5);
// For z.a_.a_ = z0.
s1 = z1.mul(x2);
t3 = s1.add(d4);
t4 = Fp6.NON_RESIDUE.mul(t3).add(d0);
z0 = t4;
// For z.a_.b_ = z1
t3 = z5.mul(x4);
s1 = s1.add(t3);
t3 = t3.add(d2);
t4 = Fp6.NON_RESIDUE.mul(t3);
t3 = z1.mul(x0);
s1 = s1.add(t3);
t4 = t4.add(t3);
z1 = t4;
// For z.a_.c_ = z2
t0 = x0.add(x2);
t3 = t1.mul(t0).sub(d0).sub(d2);
t4 = z3.mul(x4);
s1 = s1.add(t4);
t3 = t3.add(t4);
// For z.b_.a_ = z3 (z3 needs z2)
t0 = z2.add(z4);
z2 = t3;
t1 = x2.add(x4);
t3 = t0.mul(t1).sub(d2).sub(d4);
t4 = Fp6.NON_RESIDUE.mul(t3);
t3 = z3.mul(x0);
s1 = s1.add(t3);
t4 = t4.add(t3);
z3 = t4;
// For z.b_.b_ = z4
t3 = z5.mul(x2);
s1 = s1.add(t3);
t4 = Fp6.NON_RESIDUE.mul(t3);
t0 = x0.add(x4);
t3 = t2.mul(t0).sub(d0).sub(d4);
t4 = t4.add(t3);
z4 = t4;
// For z.b_.c_ = z5.
t0 = x0.add(x2).add(x4);
t3 = s0.mul(t0).sub(s1);
z5 = t3;
return new Fp12(new Fp6(z0, z1, z2), new Fp6(z3, z4, z5));
}
@Override
public Fp12 add(Fp12 o) {
return new Fp12(a.add(o.a), b.add(o.b));
}
@Override
public Fp12 mul(Fp12 o) {
Fp6 a2 = o.a, b2 = o.b;
Fp6 a1 = a, b1 = b;
Fp6 a1a2 = a1.mul(a2);
Fp6 b1b2 = b1.mul(b2);
Fp6 ra = a1a2.add(b1b2.mulByNonResidue());
Fp6 rb = a1.add(b1).mul(a2.add(b2)).sub(a1a2).sub(b1b2);
return new Fp12(ra, rb);
}
@Override
public Fp12 sub(Fp12 o) {
return new Fp12(a.sub(o.a), b.sub(o.b));
}
@Override
public Fp12 inverse() {
Fp6 t0 = a.squared();
Fp6 t1 = b.squared();
Fp6 t2 = t0.sub(t1.mulByNonResidue());
Fp6 t3 = t2.inverse();
Fp6 ra = a.mul(t3);
Fp6 rb = b.mul(t3).negate();
return new Fp12(ra, rb);
}
@Override
public Fp12 negate() {
return new Fp12(a.negate(), b.negate());
}
@Override
public boolean isZero() {
return this.equals(ZERO);
}
@Override
public boolean isValid() {
return a.isValid() && b.isValid();
}
Fp12 frobeniusMap(int power) {
Fp6 ra = a.frobeniusMap(power);
Fp6 rb = b.frobeniusMap(power).mul(FROBENIUS_COEFFS_B[power % 12]);
return new Fp12(ra, rb);
}
Fp12 cyclotomicSquared() {
Fp2 z0 = a.a;
Fp2 z4 = a.b;
Fp2 z3 = a.c;
Fp2 z2 = b.a;
Fp2 z1 = b.b;
Fp2 z5 = b.c;
Fp2 t0, t1, t2, t3, t4, t5, tmp;
// t0 + t1*y = (z0 + z1*y)^2 = a^2
tmp = z0.mul(z1);
t0 = z0.add(z1).mul(z0.add(Fp6.NON_RESIDUE.mul(z1))).sub(tmp).sub(Fp6.NON_RESIDUE.mul(tmp));
t1 = tmp.add(tmp);
// t2 + t3*y = (z2 + z3*y)^2 = b^2
tmp = z2.mul(z3);
t2 = z2.add(z3).mul(z2.add(Fp6.NON_RESIDUE.mul(z3))).sub(tmp).sub(Fp6.NON_RESIDUE.mul(tmp));
t3 = tmp.add(tmp);
// t4 + t5*y = (z4 + z5*y)^2 = c^2
tmp = z4.mul(z5);
t4 = z4.add(z5).mul(z4.add(Fp6.NON_RESIDUE.mul(z5))).sub(tmp).sub(Fp6.NON_RESIDUE.mul(tmp));
t5 = tmp.add(tmp);
// for A
// z0 = 3 * t0 - 2 * z0
z0 = t0.sub(z0);
z0 = z0.add(z0);
z0 = z0.add(t0);
// z1 = 3 * t1 + 2 * z1
z1 = t1.add(z1);
z1 = z1.add(z1);
z1 = z1.add(t1);
// for B
// z2 = 3 * (xi * t5) + 2 * z2
tmp = Fp6.NON_RESIDUE.mul(t5);
z2 = tmp.add(z2);
z2 = z2.add(z2);
z2 = z2.add(tmp);
// z3 = 3 * t4 - 2 * z3
z3 = t4.sub(z3);
z3 = z3.add(z3);
z3 = z3.add(t4);
// for C
// z4 = 3 * t2 - 2 * z4
z4 = t2.sub(z4);
z4 = z4.add(z4);
z4 = z4.add(t2);
// z5 = 3 * t3 + 2 * z5
z5 = t3.add(z5);
z5 = z5.add(z5);
z5 = z5.add(t3);
return new Fp12(new Fp6(z0, z4, z3), new Fp6(z2, z1, z5));
}
Fp12 cyclotomicExp(BigInteger pow) {
Fp12 res = _1;
for (int i = pow.bitLength() - 1; i >=0; i--) {
res = res.cyclotomicSquared();
if (pow.testBit(i)) {
res = res.mul(this);
}
}
return res;
}
Fp12 unitaryInverse() {
Fp6 ra = a;
Fp6 rb = b.negate();
return new Fp12(ra, rb);
}
Fp12 negExp(BigInteger exp) {
return this.cyclotomicExp(exp).unitaryInverse();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Fp12)) return false;
Fp12 fp12 = (Fp12) o;
if (a != null ? !a.equals(fp12.a) : fp12.a != null) return false;
return !(b != null ? !b.equals(fp12.b) : fp12.b != null);
}
@Override
public String toString() {
return String.format(
"Fp12 (%s; %s)\n" +
" (%s; %s)\n" +
" (%s; %s)\n" +
" (%s; %s)\n" +
" (%s; %s)\n" +
" (%s; %s)\n",
a.a.a, a.a.b,
a.b.a, a.b.b,
a.c.a, a.c.b,
b.a.a, b.a.b,
b.b.a, b.b.b,
b.c.a, b.c.b
);
}
static final Fp2[] FROBENIUS_COEFFS_B = new Fp2[] {
new Fp2(BigInteger.ONE,
BigInteger.ZERO),
new Fp2(new BigInteger("8376118865763821496583973867626364092589906065868298776909617916018768340080"),
new BigInteger("16469823323077808223889137241176536799009286646108169935659301613961712198316")),
new Fp2(new BigInteger("21888242871839275220042445260109153167277707414472061641714758635765020556617"),
BigInteger.ZERO),
new Fp2(new BigInteger("11697423496358154304825782922584725312912383441159505038794027105778954184319"),
new BigInteger("303847389135065887422783454877609941456349188919719272345083954437860409601")),
new Fp2(new BigInteger("21888242871839275220042445260109153167277707414472061641714758635765020556616"),
BigInteger.ZERO),
new Fp2(new BigInteger("3321304630594332808241809054958361220322477375291206261884409189760185844239"),
new BigInteger("5722266937896532885780051958958348231143373700109372999374820235121374419868")),
new Fp2(new BigInteger("21888242871839275222246405745257275088696311157297823662689037894645226208582"),
BigInteger.ZERO),
new Fp2(new BigInteger("13512124006075453725662431877630910996106405091429524885779419978626457868503"),
new BigInteger("5418419548761466998357268504080738289687024511189653727029736280683514010267")),
new Fp2(new BigInteger("2203960485148121921418603742825762020974279258880205651966"),
BigInteger.ZERO),
new Fp2(new BigInteger("10190819375481120917420622822672549775783927716138318623895010788866272024264"),
new BigInteger("21584395482704209334823622290379665147239961968378104390343953940207365798982")),
new Fp2(new BigInteger("2203960485148121921418603742825762020974279258880205651967"),
BigInteger.ZERO),
new Fp2(new BigInteger("18566938241244942414004596690298913868373833782006617400804628704885040364344"),
new BigInteger("16165975933942742336466353786298926857552937457188450663314217659523851788715"))
};
}
| 10,078
| 27.075209
| 143
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/crypto/zksnark/Fp.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.crypto.zksnark;
import java.math.BigInteger;
import static org.ethereum.crypto.zksnark.Params.P;
/**
* Arithmetic in F_p, p = 21888242871839275222246405745257275088696311157297823662689037894645226208583
*
* @author Mikhail Kalinin
* @since 01.09.2017
*/
public class Fp implements Field<Fp> {
static final Fp ZERO = new Fp(BigInteger.ZERO);
static final Fp _1 = new Fp(BigInteger.ONE);
static final Fp NON_RESIDUE = new Fp(new BigInteger("21888242871839275222246405745257275088696311157297823662689037894645226208582"));
static final Fp _2_INV = new Fp(BigInteger.valueOf(2).modInverse(P));
BigInteger v;
Fp(BigInteger v) { this.v = v; }
@Override public Fp add(Fp o) { return new Fp(this.v.add(o.v).mod(P)); }
@Override public Fp mul(Fp o) { return new Fp(this.v.multiply(o.v).mod(P)); }
@Override public Fp sub(Fp o) { return new Fp(this.v.subtract(o.v).mod(P)); }
@Override public Fp squared() { return new Fp(v.multiply(v).mod(P)); }
@Override public Fp dbl() { return new Fp(v.add(v).mod(P)); }
@Override public Fp inverse() { return new Fp(v.modInverse(P)); }
@Override public Fp negate() { return new Fp(v.negate().mod(P)); }
@Override public boolean isZero() { return v.compareTo(BigInteger.ZERO) == 0; }
/**
* Checks if provided value is a valid Fp member
*/
@Override
public boolean isValid() {
return v.compareTo(P) < 0;
}
Fp2 mul(Fp2 o) { return new Fp2(o.a.mul(this), o.b.mul(this)); }
static Fp create(byte[] v) {
return new Fp(new BigInteger(1, v));
}
static Fp create(BigInteger v) {
return new Fp(v);
}
public byte[] bytes() {
return v.toByteArray();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Fp fp = (Fp) o;
return !(v != null ? v.compareTo(fp.v) != 0 : fp.v != null);
}
@Override
public String toString() {
return v.toString();
}
}
| 2,882
| 31.761364
| 138
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/crypto/zksnark/BN128G1.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.crypto.zksnark;
/**
* Implementation of specific cyclic subgroup of points belonging to {@link BN128Fp} <br/>
* Members of this subgroup are passed as a first param to pairing input {@link PairingCheck#addPair(BN128G1, BN128G2)} <br/>
*
* Subgroup generator G = (1; 2)
*
* @author Mikhail Kalinin
* @since 01.09.2017
*/
public class BN128G1 extends BN128Fp {
BN128G1(BN128<Fp> p) {
super(p.x, p.y, p.z);
}
@Override
public BN128G1 toAffine() {
return new BN128G1(super.toAffine());
}
/**
* Checks whether point is a member of subgroup,
* returns a point if check has been passed and null otherwise
*/
public static BN128G1 create(byte[] x, byte[] y) {
BN128<Fp> p = BN128Fp.create(x, y);
if (p == null) return null;
if (!isGroupMember(p)) return null;
return new BN128G1(p);
}
/**
* Formally we have to do this check
* but in our domain it's not necessary,
* thus always return true
*/
private static boolean isGroupMember(BN128<Fp> p) {
return true;
}
}
| 1,918
| 28.984375
| 125
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/crypto/zksnark/PairingCheck.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.crypto.zksnark;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import static org.ethereum.crypto.zksnark.Params.B_Fp2;
import static org.ethereum.crypto.zksnark.Params.PAIRING_FINAL_EXPONENT_Z;
import static org.ethereum.crypto.zksnark.Params.TWIST;
/**
* Implementation of a Pairing Check operation over points of two twisted Barreto–Naehrig curves {@link BN128Fp}, {@link BN128Fp2}<br/>
* <br/>
*
* The Pairing itself is a transformation of the form G1 x G2 -> Gt, <br/>
* where G1 and G2 are members of {@link BN128G1} {@link BN128G2} respectively, <br/>
* Gt is a subgroup of roots of unity in {@link Fp12} field, root degree equals to {@link Params#R} <br/>
* <br/>
*
* Pairing Check input is a sequence of point pairs, the result is either 1 or 0, 1 is considered as success, 0 as fail <br/>
* <br/>
*
* Usage:
* <ul>
* <li>add pairs sequentially with {@link #addPair(BN128G1, BN128G2)}</li>
* <li>run check with {@link #run()} after all paris have been added</li>
* <li>get result with {@link #result()}</li>
* </ul>
*
* Arithmetic has been ported from <a href="https://github.com/scipr-lab/libff/blob/master/libff/algebra/curves/alt_bn128/alt_bn128_pairing.cpp">libff</a>
* Ate pairing algorithms
*
* @author Mikhail Kalinin
* @since 01.09.2017
*/
public class PairingCheck {
static final BigInteger LOOP_COUNT = new BigInteger("29793968203157093288");
List<Pair> pairs = new ArrayList<>();
Fp12 product = Fp12._1;
private PairingCheck() {}
public static PairingCheck create() {
return new PairingCheck();
}
public void addPair(BN128G1 g1, BN128G2 g2) {
pairs.add(Pair.of(g1, g2));
}
public void run() {
for (Pair pair : pairs) {
Fp12 miller = pair.millerLoop();
if (!miller.equals(Fp12._1)) // run mul code only if necessary
product = product.mul(miller);
}
// finalize
product = finalExponentiation(product);
}
public int result() {
return product.equals(Fp12._1) ? 1 : 0;
}
private static Fp12 millerLoop(BN128G1 g1, BN128G2 g2) {
// convert to affine coordinates
g1 = g1.toAffine();
g2 = g2.toAffine();
// calculate Ell coefficients
List<EllCoeffs> coeffs = calcEllCoeffs(g2);
Fp12 f = Fp12._1;
int idx = 0;
// for each bit except most significant one
for (int i = LOOP_COUNT.bitLength() - 2; i >=0; i--) {
EllCoeffs c = coeffs.get(idx++);
f = f.squared();
f = f.mulBy024(c.ell0, g1.y.mul(c.ellVW), g1.x.mul(c.ellVV));
if (LOOP_COUNT.testBit(i)) {
c = coeffs.get(idx++);
f = f.mulBy024(c.ell0, g1.y.mul(c.ellVW), g1.x.mul(c.ellVV));
}
}
EllCoeffs c = coeffs.get(idx++);
f = f.mulBy024(c.ell0, g1.y.mul(c.ellVW), g1.x.mul(c.ellVV));
c = coeffs.get(idx);
f = f.mulBy024(c.ell0, g1.y.mul(c.ellVW), g1.x.mul(c.ellVV));
return f;
}
private static List<EllCoeffs> calcEllCoeffs(BN128G2 base) {
List<EllCoeffs> coeffs = new ArrayList<>();
BN128G2 addend = base;
// for each bit except most significant one
for (int i = LOOP_COUNT.bitLength() - 2; i >=0; i--) {
Precomputed doubling = flippedMillerLoopDoubling(addend);
addend = doubling.g2;
coeffs.add(doubling.coeffs);
if (LOOP_COUNT.testBit(i)) {
Precomputed addition = flippedMillerLoopMixedAddition(base, addend);
addend = addition.g2;
coeffs.add(addition.coeffs);
}
}
BN128G2 q1 = base.mulByP();
BN128G2 q2 = q1.mulByP();
q2 = new BN128G2(q2.x, q2.y.negate(), q2.z) ; // q2.y = -q2.y
Precomputed addition = flippedMillerLoopMixedAddition(q1, addend);
addend = addition.g2;
coeffs.add(addition.coeffs);
addition = flippedMillerLoopMixedAddition(q2, addend);
coeffs.add(addition.coeffs);
return coeffs;
}
private static Precomputed flippedMillerLoopMixedAddition(BN128G2 base, BN128G2 addend) {
Fp2 x1 = addend.x, y1 = addend.y, z1 = addend.z;
Fp2 x2 = base.x, y2 = base.y;
Fp2 d = x1.sub(x2.mul(z1)); // d = x1 - x2 * z1
Fp2 e = y1.sub(y2.mul(z1)); // e = y1 - y2 * z1
Fp2 f = d.squared(); // f = d^2
Fp2 g = e.squared(); // g = e^2
Fp2 h = d.mul(f); // h = d * f
Fp2 i = x1.mul(f); // i = x1 * f
Fp2 j = h.add(z1.mul(g)).sub(i.dbl()); // j = h + z1 * g - 2 * i
Fp2 x3 = d.mul(j); // x3 = d * j
Fp2 y3 = e.mul(i.sub(j)).sub(h.mul(y1)); // y3 = e * (i - j) - h * y1)
Fp2 z3 = z1.mul(h); // z3 = Z1*H
Fp2 ell0 = TWIST.mul(e.mul(x2).sub(d.mul(y2))); // ell_0 = TWIST * (e * x2 - d * y2)
Fp2 ellVV = e.negate(); // ell_VV = -e
Fp2 ellVW = d; // ell_VW = d
return Precomputed.of(
new BN128G2(x3, y3, z3),
new EllCoeffs(ell0, ellVW, ellVV)
);
}
private static Precomputed flippedMillerLoopDoubling(BN128G2 g2) {
Fp2 x = g2.x, y = g2.y, z = g2.z;
Fp2 a = Fp._2_INV.mul(x.mul(y)); // a = x * y / 2
Fp2 b = y.squared(); // b = y^2
Fp2 c = z.squared(); // c = z^2
Fp2 d = c.add(c).add(c); // d = 3 * c
Fp2 e = B_Fp2.mul(d); // e = twist_b * d
Fp2 f = e.add(e).add(e); // f = 3 * e
Fp2 g = Fp._2_INV.mul(b.add(f)); // g = (b + f) / 2
Fp2 h = y.add(z).squared().sub(b.add(c)); // h = (y + z)^2 - (b + c)
Fp2 i = e.sub(b); // i = e - b
Fp2 j = x.squared(); // j = x^2
Fp2 e2 = e.squared(); // e2 = e^2
Fp2 rx = a.mul(b.sub(f)); // rx = a * (b - f)
Fp2 ry = g.squared().sub(e2.add(e2).add(e2)); // ry = g^2 - 3 * e^2
Fp2 rz = b.mul(h); // rz = b * h
Fp2 ell0 = TWIST.mul(i); // ell_0 = twist * i
Fp2 ellVW = h.negate(); // ell_VW = -h
Fp2 ellVV = j.add(j).add(j); // ell_VV = 3 * j
return Precomputed.of(
new BN128G2(rx, ry, rz),
new EllCoeffs(ell0, ellVW, ellVV)
);
}
public static Fp12 finalExponentiation(Fp12 el) {
// first chunk
Fp12 w = new Fp12(el.a, el.b.negate()); // el.b = -el.b
Fp12 x = el.inverse();
Fp12 y = w.mul(x);
Fp12 z = y.frobeniusMap(2);
Fp12 pre = z.mul(y);
// last chunk
Fp12 a = pre.negExp(PAIRING_FINAL_EXPONENT_Z);
Fp12 b = a.cyclotomicSquared();
Fp12 c = b.cyclotomicSquared();
Fp12 d = c.mul(b);
Fp12 e = d.negExp(PAIRING_FINAL_EXPONENT_Z);
Fp12 f = e.cyclotomicSquared();
Fp12 g = f.negExp(PAIRING_FINAL_EXPONENT_Z);
Fp12 h = d.unitaryInverse();
Fp12 i = g.unitaryInverse();
Fp12 j = i.mul(e);
Fp12 k = j.mul(h);
Fp12 l = k.mul(b);
Fp12 m = k.mul(e);
Fp12 n = m.mul(pre);
Fp12 o = l.frobeniusMap(1);
Fp12 p = o.mul(n);
Fp12 q = k.frobeniusMap(2);
Fp12 r = q.mul(p);
Fp12 s = pre.unitaryInverse();
Fp12 t = s.mul(l);
Fp12 u = t.frobeniusMap(3);
Fp12 v = u.mul(r);
return v;
}
static class Precomputed {
BN128G2 g2;
EllCoeffs coeffs;
static Precomputed of(BN128G2 g2, EllCoeffs coeffs) {
return new Precomputed(g2, coeffs);
}
Precomputed(BN128G2 g2, EllCoeffs coeffs) {
this.g2 = g2;
this.coeffs = coeffs;
}
}
static class Pair {
BN128G1 g1;
BN128G2 g2;
static Pair of(BN128G1 g1, BN128G2 g2) {
return new Pair(g1, g2);
}
Pair(BN128G1 g1, BN128G2 g2) {
this.g1 = g1;
this.g2 = g2;
}
Fp12 millerLoop() {
// miller loop result equals "1" if at least one of the points is zero
if (g1.isZero()) return Fp12._1;
if (g2.isZero()) return Fp12._1;
return PairingCheck.millerLoop(g1, g2);
}
}
static class EllCoeffs {
Fp2 ell0;
Fp2 ellVW;
Fp2 ellVV;
EllCoeffs(Fp2 ell0, Fp2 ellVW, Fp2 ellVV) {
this.ell0 = ell0;
this.ellVW = ellVW;
this.ellVV = ellVV;
}
}
}
| 9,832
| 31.452145
| 154
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/crypto/zksnark/BN128G2.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.crypto.zksnark;
import java.math.BigInteger;
import static org.ethereum.crypto.zksnark.Params.R;
import static org.ethereum.crypto.zksnark.Params.TWIST_MUL_BY_P_X;
import static org.ethereum.crypto.zksnark.Params.TWIST_MUL_BY_P_Y;
/**
* Implementation of specific cyclic subgroup of points belonging to {@link BN128Fp2} <br/>
* Members of this subgroup are passed as a second param to pairing input {@link PairingCheck#addPair(BN128G1, BN128G2)} <br/>
* <br/>
*
* The order of subgroup is {@link Params#R} <br/>
* Generator of subgroup G = <br/>
* (11559732032986387107991004021392285783925812861821192530917403151452391805634 * i + <br/>
* 10857046999023057135944570762232829481370756359578518086990519993285655852781, <br/>
* 4082367875863433681332203403145435568316851327593401208105741076214120093531 * i + <br/>
* 8495653923123431417604973247489272438418190587263600148770280649306958101930) <br/>
* <br/>
*
* @author Mikhail Kalinin
* @since 31.08.2017
*/
public class BN128G2 extends BN128Fp2 {
BN128G2(BN128<Fp2> p) {
super(p.x, p.y, p.z);
}
BN128G2(Fp2 x, Fp2 y, Fp2 z) {
super(x, y, z);
}
@Override
public BN128G2 toAffine() {
return new BN128G2(super.toAffine());
}
/**
* Checks whether provided data are coordinates of a point belonging to subgroup,
* if check has been passed it returns a point, otherwise returns null
*/
public static BN128G2 create(byte[] a, byte[] b, byte[] c, byte[] d) {
BN128<Fp2> p = BN128Fp2.create(a, b, c, d);
// fails if point is invalid
if (p == null) {
return null;
}
// check whether point is a subgroup member
if (!isGroupMember(p)) return null;
return new BN128G2(p);
}
private static boolean isGroupMember(BN128<Fp2> p) {
BN128<Fp2> left = p.mul(FR_NEG_ONE).add(p);
return left.isZero(); // should satisfy condition: -1 * p + p == 0, where -1 belongs to F_r
}
static final BigInteger FR_NEG_ONE = BigInteger.ONE.negate().mod(R);
BN128G2 mulByP() {
Fp2 rx = TWIST_MUL_BY_P_X.mul(x.frobeniusMap(1));
Fp2 ry = TWIST_MUL_BY_P_Y.mul(y.frobeniusMap(1));
Fp2 rz = z.frobeniusMap(1);
return new BN128G2(rx, ry, rz);
}
}
| 3,118
| 33.274725
| 126
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/crypto/zksnark/BN128Fp2.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.crypto.zksnark;
import java.math.BigInteger;
import static org.ethereum.crypto.zksnark.Params.B_Fp2;
/**
* Definition of {@link BN128} over F_p2, where "p" equals {@link Params#P} <br/>
*
* Curve equation: <br/>
* Y^2 = X^3 + b, where "b" equals {@link Params#B_Fp2} <br/>
*
* @author Mikhail Kalinin
* @since 31.08.2017
*/
public class BN128Fp2 extends BN128<Fp2> {
// the point at infinity
static final BN128<Fp2> ZERO = new BN128Fp2(Fp2.ZERO, Fp2.ZERO, Fp2.ZERO);
protected BN128Fp2(Fp2 x, Fp2 y, Fp2 z) {
super(x, y, z);
}
@Override
protected BN128<Fp2> zero() {
return ZERO;
}
@Override
protected BN128<Fp2> instance(Fp2 x, Fp2 y, Fp2 z) {
return new BN128Fp2(x, y, z);
}
@Override
protected Fp2 b() {
return B_Fp2;
}
@Override
protected Fp2 one() {
return Fp2._1;
}
protected BN128Fp2(BigInteger a, BigInteger b, BigInteger c, BigInteger d) {
super(Fp2.create(a, b), Fp2.create(c, d), Fp2._1);
}
/**
* Checks whether provided data are coordinates of a point on the curve,
* then checks if this point is a member of subgroup of order "r"
* and if checks have been passed it returns a point, otherwise returns null
*/
public static BN128<Fp2> create(byte[] aa, byte[] bb, byte[] cc, byte[] dd) {
Fp2 x = Fp2.create(aa, bb);
Fp2 y = Fp2.create(cc, dd);
// check for point at infinity
if (x.isZero() && y.isZero()) {
return ZERO;
}
BN128<Fp2> p = new BN128Fp2(x, y, Fp2._1);
// check whether point is a valid one
if (p.isValid()) {
return p;
} else {
return null;
}
}
}
| 2,574
| 27.296703
| 81
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/crypto/zksnark/Field.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.crypto.zksnark;
/**
* Interface of abstract finite field
*
* @author Mikhail Kalinin
* @since 05.09.2017
*/
interface Field<T> {
T add(T o);
T mul(T o);
T sub(T o);
T squared();
T dbl();
T inverse();
T negate();
boolean isZero();
boolean isValid();
}
| 1,105
| 28.105263
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/crypto/zksnark/Fp6.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.crypto.zksnark;
import java.math.BigInteger;
/**
* Arithmetic in Fp_6 <br/>
* <br/>
*
* "p" equals 21888242871839275222246405745257275088696311157297823662689037894645226208583, <br/>
* elements of Fp_6 are represented with 3 elements of {@link Fp2} <br/>
* <br/>
*
* Field arithmetic is ported from <a href="https://github.com/scipr-lab/libff/blob/master/libff/algebra/fields/fp6_3over2.tcc">libff</a>
*
* @author Mikhail Kalinin
* @since 05.09.2017
*/
class Fp6 implements Field<Fp6> {
static final Fp6 ZERO = new Fp6(Fp2.ZERO, Fp2.ZERO, Fp2.ZERO);
static final Fp6 _1 = new Fp6(Fp2._1, Fp2.ZERO, Fp2.ZERO);
static final Fp2 NON_RESIDUE = new Fp2(BigInteger.valueOf(9), BigInteger.ONE);
Fp2 a;
Fp2 b;
Fp2 c;
Fp6(Fp2 a, Fp2 b, Fp2 c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public Fp6 squared() {
Fp2 s0 = a.squared();
Fp2 ab = a.mul(b);
Fp2 s1 = ab.dbl();
Fp2 s2 = a.sub(b).add(c).squared();
Fp2 bc = b.mul(c);
Fp2 s3 = bc.dbl();
Fp2 s4 = c.squared();
Fp2 ra = s0.add(s3.mulByNonResidue());
Fp2 rb = s1.add(s4.mulByNonResidue());
Fp2 rc = s1.add(s2).add(s3).sub(s0).sub(s4);
return new Fp6(ra, rb, rc);
}
@Override
public Fp6 dbl() {
return this.add(this);
}
@Override
public Fp6 mul(Fp6 o) {
Fp2 a1 = a, b1 = b, c1 = c;
Fp2 a2 = o.a, b2 = o.b, c2 = o.c;
Fp2 a1a2 = a1.mul(a2);
Fp2 b1b2 = b1.mul(b2);
Fp2 c1c2 = c1.mul(c2);
Fp2 ra = a1a2.add(b1.add(c1).mul(b2.add(c2)).sub(b1b2).sub(c1c2).mulByNonResidue());
Fp2 rb = a1.add(b1).mul(a2.add(b2)).sub(a1a2).sub(b1b2).add(c1c2.mulByNonResidue());
Fp2 rc = a1.add(c1).mul(a2.add(c2)).sub(a1a2).add(b1b2).sub(c1c2);
return new Fp6(ra, rb, rc);
}
Fp6 mul(Fp2 o) {
Fp2 ra = a.mul(o);
Fp2 rb = b.mul(o);
Fp2 rc = c.mul(o);
return new Fp6(ra, rb, rc);
}
Fp6 mulByNonResidue() {
Fp2 ra = NON_RESIDUE.mul(c);
Fp2 rb = a;
Fp2 rc = b;
return new Fp6(ra, rb, rc);
}
@Override
public Fp6 add(Fp6 o) {
Fp2 ra = a.add(o.a);
Fp2 rb = b.add(o.b);
Fp2 rc = c.add(o.c);
return new Fp6(ra, rb, rc);
}
@Override
public Fp6 sub(Fp6 o) {
Fp2 ra = a.sub(o.a);
Fp2 rb = b.sub(o.b);
Fp2 rc = c.sub(o.c);
return new Fp6(ra, rb, rc);
}
@Override
public Fp6 inverse() {
/* From "High-Speed Software Implementation of the Optimal Ate Pairing over Barreto-Naehrig Curves"; Algorithm 17 */
Fp2 t0 = a.squared();
Fp2 t1 = b.squared();
Fp2 t2 = c.squared();
Fp2 t3 = a.mul(b);
Fp2 t4 = a.mul(c);
Fp2 t5 = b.mul(c);
Fp2 c0 = t0.sub(t5.mulByNonResidue());
Fp2 c1 = t2.mulByNonResidue().sub(t3);
Fp2 c2 = t1.sub(t4); // typo in paper referenced above. should be "-" as per Scott, but is "*"
Fp2 t6 = a.mul(c0).add((c.mul(c1).add(b.mul(c2))).mulByNonResidue()).inverse();
Fp2 ra = t6.mul(c0);
Fp2 rb = t6.mul(c1);
Fp2 rc = t6.mul(c2);
return new Fp6(ra, rb, rc);
}
@Override
public Fp6 negate() {
return new Fp6(a.negate(), b.negate(), c.negate());
}
@Override
public boolean isZero() {
return this.equals(ZERO);
}
@Override
public boolean isValid() {
return a.isValid() && b.isValid() && c.isValid();
}
Fp6 frobeniusMap(int power) {
Fp2 ra = a.frobeniusMap(power);
Fp2 rb = FROBENIUS_COEFFS_B[power % 6].mul(b.frobeniusMap(power));
Fp2 rc = FROBENIUS_COEFFS_C[power % 6].mul(c.frobeniusMap(power));
return new Fp6(ra, rb, rc);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Fp6)) return false;
Fp6 fp6 = (Fp6) o;
if (a != null ? !a.equals(fp6.a) : fp6.a != null) return false;
if (b != null ? !b.equals(fp6.b) : fp6.b != null) return false;
return !(c != null ? !c.equals(fp6.c) : fp6.c != null);
}
static final Fp2[] FROBENIUS_COEFFS_B = {
new Fp2(BigInteger.ONE,
BigInteger.ZERO),
new Fp2(new BigInteger("21575463638280843010398324269430826099269044274347216827212613867836435027261"),
new BigInteger("10307601595873709700152284273816112264069230130616436755625194854815875713954")),
new Fp2(new BigInteger("21888242871839275220042445260109153167277707414472061641714758635765020556616"),
BigInteger.ZERO),
new Fp2(new BigInteger("3772000881919853776433695186713858239009073593817195771773381919316419345261"),
new BigInteger("2236595495967245188281701248203181795121068902605861227855261137820944008926")),
new Fp2(new BigInteger("2203960485148121921418603742825762020974279258880205651966"),
BigInteger.ZERO),
new Fp2(new BigInteger("18429021223477853657660792034369865839114504446431234726392080002137598044644"),
new BigInteger("9344045779998320333812420223237981029506012124075525679208581902008406485703"))
};
static final Fp2[] FROBENIUS_COEFFS_C = {
new Fp2(BigInteger.ONE,
BigInteger.ZERO),
new Fp2(new BigInteger("2581911344467009335267311115468803099551665605076196740867805258568234346338"),
new BigInteger("19937756971775647987995932169929341994314640652964949448313374472400716661030")),
new Fp2(new BigInteger("2203960485148121921418603742825762020974279258880205651966"),
BigInteger.ZERO),
new Fp2(new BigInteger("5324479202449903542726783395506214481928257762400643279780343368557297135718"),
new BigInteger("16208900380737693084919495127334387981393726419856888799917914180988844123039")),
new Fp2(new BigInteger("21888242871839275220042445260109153167277707414472061641714758635765020556616"),
BigInteger.ZERO),
new Fp2(new BigInteger("13981852324922362344252311234282257507216387789820983642040889267519694726527"),
new BigInteger("7629828391165209371577384193250820201684255241773809077146787135900891633097"))
};
}
| 7,310
| 30.786957
| 137
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/crypto/zksnark/Params.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.crypto.zksnark;
import java.math.BigInteger;
/**
* Common params for BN curves, its derivatives and pairing
*
* @author Mikhail Kalinin
* @since 31.08.2017
*/
class Params {
/**
* "p" field parameter of F_p, F_p2, F_p6 and F_p12
*/
static final BigInteger P = new BigInteger("21888242871839275222246405745257275088696311157297823662689037894645226208583");
/**
* "r" order of {@link BN128G2} cyclic subgroup
*/
static final BigInteger R = new BigInteger("21888242871839275222246405745257275088548364400416034343698204186575808495617");
/**
* "b" curve parameter for {@link BN128Fp}
*/
static final Fp B_Fp = Fp.create(BigInteger.valueOf(3));
/**
* Twist parameter for the curves
*/
static final Fp2 TWIST = Fp2.create(BigInteger.valueOf(9), BigInteger.valueOf(1));
/**
* "b" curve parameter for {@link BN128Fp2}
*/
static final Fp2 B_Fp2 = B_Fp.mul(TWIST.inverse());
static final Fp2 TWIST_MUL_BY_P_X = Fp2.create(
new BigInteger("21575463638280843010398324269430826099269044274347216827212613867836435027261"),
new BigInteger("10307601595873709700152284273816112264069230130616436755625194854815875713954")
);
static final Fp2 TWIST_MUL_BY_P_Y = Fp2.create(
new BigInteger("2821565182194536844548159561693502659359617185244120367078079554186484126554"),
new BigInteger("3505843767911556378687030309984248845540243509899259641013678093033130930403")
);
static final BigInteger PAIRING_FINAL_EXPONENT_Z = new BigInteger("4965661367192848881");
}
| 2,429
| 35.268657
| 128
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/crypto/zksnark/BN128Fp.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.crypto.zksnark;
import static org.ethereum.crypto.zksnark.Params.B_Fp;
/**
* Definition of {@link BN128} over F_p, where "p" equals {@link Params#P} <br/>
*
* Curve equation: <br/>
* Y^2 = X^3 + b, where "b" equals {@link Params#B_Fp} <br/>
*
* @author Mikhail Kalinin
* @since 21.08.2017
*/
public class BN128Fp extends BN128<Fp> {
// the point at infinity
static final BN128<Fp> ZERO = new BN128Fp(Fp.ZERO, Fp.ZERO, Fp.ZERO);
protected BN128Fp(Fp x, Fp y, Fp z) {
super(x, y, z);
}
@Override
protected BN128<Fp> zero() {
return ZERO;
}
@Override
protected BN128<Fp> instance(Fp x, Fp y, Fp z) {
return new BN128Fp(x, y, z);
}
@Override
protected Fp b() {
return B_Fp;
}
@Override
protected Fp one() {
return Fp._1;
}
/**
* Checks whether x and y belong to Fp,
* then checks whether point with (x; y) coordinates lays on the curve.
*
* Returns new point if all checks have been passed,
* otherwise returns null
*/
public static BN128<Fp> create(byte[] xx, byte[] yy) {
Fp x = Fp.create(xx);
Fp y = Fp.create(yy);
// check for point at infinity
if (x.isZero() && y.isZero()) {
return ZERO;
}
BN128<Fp> p = new BN128Fp(x, y, Fp._1);
// check whether point is a valid one
if (p.isValid()) {
return p;
} else {
return null;
}
}
}
| 2,321
| 25.689655
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/crypto/zksnark/Fp2.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.crypto.zksnark;
import java.math.BigInteger;
/**
* Arithmetic in F_p2 <br/>
* <br/>
*
* "p" equals 21888242871839275222246405745257275088696311157297823662689037894645226208583,
* elements of F_p2 are represented as a polynomials "a * i + b" modulo "i^2 + 1" from the ring F_p[i] <br/>
* <br/>
*
* Field arithmetic is ported from <a href="https://github.com/scipr-lab/libff/blob/master/libff/algebra/fields/fp2.tcc">libff</a> <br/>
*
* @author Mikhail Kalinin
* @since 01.09.2017
*/
class Fp2 implements Field<Fp2> {
static final Fp2 ZERO = new Fp2(Fp.ZERO, Fp.ZERO);
static final Fp2 _1 = new Fp2(Fp._1, Fp.ZERO);
static final Fp2 NON_RESIDUE = new Fp2(BigInteger.valueOf(9), BigInteger.ONE);
static final Fp[] FROBENIUS_COEFFS_B = new Fp[] {
new Fp(BigInteger.ONE),
new Fp(new BigInteger("21888242871839275222246405745257275088696311157297823662689037894645226208582"))
};
Fp a;
Fp b;
Fp2(Fp a, Fp b) {
this.a = a;
this.b = b;
}
Fp2(BigInteger a, BigInteger b) {
this(new Fp(a), new Fp(b));
}
@Override
public Fp2 squared() {
// using Complex squaring
Fp ab = a.mul(b);
Fp ra = a.add(b).mul(b.mul(Fp.NON_RESIDUE).add(a))
.sub(ab).sub(ab.mul(Fp.NON_RESIDUE)); // ra = (a + b)(a + NON_RESIDUE * b) - ab - NON_RESIDUE * b
Fp rb = ab.dbl();
return new Fp2(ra, rb);
}
@Override
public Fp2 mul(Fp2 o) {
Fp aa = a.mul(o.a);
Fp bb = b.mul(o.b);
Fp ra = bb.mul(Fp.NON_RESIDUE).add(aa); // ra = a1 * a2 + NON_RESIDUE * b1 * b2
Fp rb = a.add(b).mul(o.a.add(o.b)).sub(aa).sub(bb); // rb = (a1 + b1)(a2 + b2) - a1 * a2 - b1 * b2
return new Fp2(ra, rb);
}
@Override
public Fp2 add(Fp2 o) {
return new Fp2(a.add(o.a), b.add(o.b));
}
@Override
public Fp2 sub(Fp2 o) {
return new Fp2(a.sub(o.a), b.sub(o.b));
}
@Override
public Fp2 dbl() {
return this.add(this);
}
@Override
public Fp2 inverse() {
Fp t0 = a.squared();
Fp t1 = b.squared();
Fp t2 = t0.sub(Fp.NON_RESIDUE.mul(t1));
Fp t3 = t2.inverse();
Fp ra = a.mul(t3); // ra = a * t3
Fp rb = b.mul(t3).negate(); // rb = -(b * t3)
return new Fp2(ra, rb);
}
@Override
public Fp2 negate() {
return new Fp2(a.negate(), b.negate());
}
@Override
public boolean isZero() {
return this.equals(ZERO);
}
@Override
public boolean isValid() {
return a.isValid() && b.isValid();
}
static Fp2 create(BigInteger aa, BigInteger bb) {
Fp a = Fp.create(aa);
Fp b = Fp.create(bb);
return new Fp2(a, b);
}
static Fp2 create(byte[] aa, byte[] bb) {
Fp a = Fp.create(aa);
Fp b = Fp.create(bb);
return new Fp2(a, b);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Fp2 fp2 = (Fp2) o;
if (a != null ? !a.equals(fp2.a) : fp2.a != null) return false;
return !(b != null ? !b.equals(fp2.b) : fp2.b != null);
}
Fp2 frobeniusMap(int power) {
Fp ra = a;
Fp rb = FROBENIUS_COEFFS_B[power % 2].mul(b);
return new Fp2(ra, rb);
}
Fp2 mulByNonResidue() {
return NON_RESIDUE.mul(this);
}
@Override
public String toString() {
return String.format("%si + %s", a.toString(), b.toString());
}
}
| 4,442
| 24.682081
| 136
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/crypto/zksnark/BN128.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.crypto.zksnark;
import java.math.BigInteger;
/**
* Implementation of Barreto–Naehrig curve defined over abstract finite field. This curve is one of the keys to zkSNARKs. <br/>
* This specific curve was introduced in
* <a href="https://github.com/scipr-lab/libff#elliptic-curve-choices">libff</a>
* and used by a proving system in
* <a href="https://github.com/zcash/zcash/wiki/specification#zcash-protocol">ZCash protocol</a> <br/>
* <br/>
*
* Curve equation: <br/>
* Y^2 = X^3 + b, where "b" is a constant number belonging to corresponding specific field <br/>
* Point at infinity is encoded as <code>(0, 0, 0)</code> <br/>
* <br/>
*
* This curve has embedding degree 12 with respect to "r" (see {@link Params#R}), which means that "r" is a multiple of "p ^ 12 - 1",
* this condition is important for pairing operation implemented in {@link PairingCheck}<br/>
* <br/>
*
* Code of curve arithmetic has been ported from
* <a href="https://github.com/scipr-lab/libff/blob/master/libff/algebra/curves/alt_bn128/alt_bn128_g1.cpp">libff</a> <br/>
* <br/>
*
* Current implementation uses Jacobian coordinate system as
* <a href="https://github.com/scipr-lab/libff/blob/master/libff/algebra/curves/alt_bn128/alt_bn128_g1.cpp">libff</a> does,
* use {@link #toEthNotation()} to convert Jacobian coords to Ethereum encoding <br/>
*
* @author Mikhail Kalinin
* @since 05.09.2017
*/
public abstract class BN128<T extends Field<T>> {
protected T x;
protected T y;
protected T z;
protected BN128(T x, T y, T z) {
this.x = x;
this.y = y;
this.z = z;
}
/**
* Point at infinity in Ethereum notation: should return (0; 0; 0),
* {@link #isZero()} method called for that point, also, returns {@code true}
*/
abstract protected BN128<T> zero();
abstract protected BN128<T> instance(T x, T y, T z);
abstract protected T b();
abstract protected T one();
/**
* Transforms given Jacobian to affine coordinates and then creates a point
*/
public BN128<T> toAffine() {
if (isZero()) {
BN128<T> zero = zero();
return instance(zero.x, one(), zero.z); // (0; 1; 0)
}
T zInv = z.inverse();
T zInv2 = zInv.squared();
T zInv3 = zInv2.mul(zInv);
T ax = x.mul(zInv2);
T ay = y.mul(zInv3);
return instance(ax, ay, one());
}
/**
* Runs affine transformation and encodes point at infinity as (0; 0; 0)
*/
public BN128<T> toEthNotation() {
BN128<T> affine = toAffine();
// affine zero is (0; 1; 0), convert to Ethereum zero: (0; 0; 0)
if (affine.isZero()) {
return zero();
} else {
return affine;
}
}
protected boolean isOnCurve() {
if (isZero()) return true;
T z6 = z.squared().mul(z).squared();
T left = y.squared(); // y^2
T right = x.squared().mul(x).add(b().mul(z6)); // x^3 + b * z^6
return left.equals(right);
}
public BN128<T> add(BN128<T> o) {
if (this.isZero()) return o; // 0 + P = P
if (o.isZero()) return this; // P + 0 = P
T x1 = this.x, y1 = this.y, z1 = this.z;
T x2 = o.x, y2 = o.y, z2 = o.z;
// ported code is started from here
// next calculations are done in Jacobian coordinates
T z1z1 = z1.squared();
T z2z2 = z2.squared();
T u1 = x1.mul(z2z2);
T u2 = x2.mul(z1z1);
T z1Cubed = z1.mul(z1z1);
T z2Cubed = z2.mul(z2z2);
T s1 = y1.mul(z2Cubed); // s1 = y1 * Z2^3
T s2 = y2.mul(z1Cubed); // s2 = y2 * Z1^3
if (u1.equals(u2) && s1.equals(s2)) {
return dbl(); // P + P = 2P
}
T h = u2.sub(u1); // h = u2 - u1
T i = h.dbl().squared(); // i = (2 * h)^2
T j = h.mul(i); // j = h * i
T r = s2.sub(s1).dbl(); // r = 2 * (s2 - s1)
T v = u1.mul(i); // v = u1 * i
T zz = z1.add(z2).squared()
.sub(z1.squared()).sub(z2.squared());
T x3 = r.squared().sub(j).sub(v.dbl()); // x3 = r^2 - j - 2 * v
T y3 = v.sub(x3).mul(r).sub(s1.mul(j).dbl()); // y3 = r * (v - x3) - 2 * (s1 * j)
T z3 = zz.mul(h); // z3 = ((z1+z2)^2 - z1^2 - z2^2) * h = zz * h
return instance(x3, y3, z3);
}
public BN128<T> mul(BigInteger s) {
if (s.compareTo(BigInteger.ZERO) == 0) // P * 0 = 0
return zero();
if (isZero()) return this; // 0 * s = 0
BN128<T> res = zero();
for (int i = s.bitLength() - 1; i >= 0; i--) {
res = res.dbl();
if (s.testBit(i)) {
res = res.add(this);
}
}
return res;
}
private BN128<T> dbl() {
if (isZero()) return this;
// ported code is started from here
// next calculations are done in Jacobian coordinates with z = 1
T a = x.squared(); // a = x^2
T b = y.squared(); // b = y^2
T c = b.squared(); // c = b^2
T d = x.add(b).squared().sub(a).sub(c);
d = d.add(d); // d = 2 * ((x + b)^2 - a - c)
T e = a.add(a).add(a); // e = 3 * a
T f = e.squared(); // f = e^2
T x3 = f.sub(d.add(d)); // rx = f - 2 * d
T y3 = e.mul(d.sub(x3)).sub(c.dbl().dbl().dbl()); // ry = e * (d - rx) - 8 * c
T z3 = y.mul(z).dbl(); // z3 = 2 * y * z
return instance(x3, y3, z3);
}
public T x() {
return x;
}
public T y() {
return y;
}
public boolean isZero() {
return z.isZero();
}
protected boolean isValid() {
// check whether coordinates belongs to the Field
if (!x.isValid() || !y.isValid() || !z.isValid()) {
return false;
}
// check whether point is on the curve
if (!isOnCurve()) {
return false;
}
return true;
}
@Override
public String toString() {
return String.format("(%s; %s; %s)", x.toString(), y.toString(), z.toString());
}
@Override
@SuppressWarnings("all")
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof BN128)) return false;
BN128<?> bn128 = (BN128<?>) o;
if (x != null ? !x.equals(bn128.x) : bn128.x != null) return false;
if (y != null ? !y.equals(bn128.y) : bn128.y != null) return false;
return !(z != null ? !z.equals(bn128.z) : bn128.z != null);
}
}
| 7,494
| 29.46748
| 133
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/validator/ValidationRule.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.validator;
import java.util.List;
/**
* Topmost interface for validation rules
*
* @author Mikhail Kalinin
* @since 02.09.2015
*/
public interface ValidationRule {
/**
* Returns errors occurred during most recent validation run
*
* @return list of errors
*/
List<String> getErrors();
}
| 1,133
| 29.648649
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/validator/ParentBlockHeaderValidator.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.validator;
import org.ethereum.core.BlockHeader;
import java.util.List;
/**
* Composite {@link BlockHeader} validator
* aggregating list of simple validation rules depending on parent's block header
*
* @author Mikhail Kalinin
* @since 02.09.2015
*/
public class ParentBlockHeaderValidator extends DependentBlockHeaderRule {
private List<DependentBlockHeaderRule> rules;
public ParentBlockHeaderValidator(List<DependentBlockHeaderRule> rules) {
this.rules = rules;
}
@Override
public boolean validate(BlockHeader header, BlockHeader parent) {
errors.clear();
for (DependentBlockHeaderRule rule : rules) {
if (!rule.validate(header, parent)) {
errors.addAll(rule.getErrors());
return false;
}
}
return true;
}
}
| 1,656
| 30.264151
| 81
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/validator/ExtraDataRule.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.validator;
import org.ethereum.config.Constants;
import org.ethereum.config.SystemProperties;
import org.ethereum.core.BlockHeader;
/**
* Checks {@link BlockHeader#extraData} size against {@link Constants#getMAXIMUM_EXTRA_DATA_SIZE}
*
* @author Mikhail Kalinin
* @since 02.09.2015
*/
public class ExtraDataRule extends BlockHeaderRule {
private final int MAXIMUM_EXTRA_DATA_SIZE;
public ExtraDataRule(SystemProperties config) {
MAXIMUM_EXTRA_DATA_SIZE = config.getBlockchainConfig().
getCommonConstants().getMAXIMUM_EXTRA_DATA_SIZE();
}
@Override
public ValidationResult validate(BlockHeader header) {
if (header.getExtraData() != null && header.getExtraData().length > MAXIMUM_EXTRA_DATA_SIZE) {
return fault(String.format(
"#%d: header.getExtraData().length > MAXIMUM_EXTRA_DATA_SIZE",
header.getNumber()
));
}
return Success;
}
}
| 1,791
| 34.137255
| 102
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/validator/BlockHeaderRule.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.validator;
import org.ethereum.core.BlockHeader;
import org.slf4j.Logger;
/**
* Parent class for {@link BlockHeader} validators
*
* @author Mikhail Kalinin
* @since 02.09.2015
*/
public abstract class BlockHeaderRule extends AbstractValidationRule {
@Override
public Class getEntityClass() {
return BlockHeader.class;
}
/**
* Runs header validation and returns its result
*
* @param header block header
*/
abstract public ValidationResult validate(BlockHeader header);
protected ValidationResult fault(String error) {
return new ValidationResult(false, error);
}
public static final ValidationResult Success = new ValidationResult(true, null);
public boolean validateAndLog(BlockHeader header, Logger logger) {
ValidationResult result = validate(header);
if (!result.success && logger.isErrorEnabled()) {
logger.warn("{} invalid {}", getEntityClass(), result.error);
}
return result.success;
}
/**
* Validation result is either success or fault
*/
public static final class ValidationResult {
public final boolean success;
public final String error;
public ValidationResult(boolean success, String error) {
this.success = success;
this.error = error;
}
@Override
public String toString() {
return (success ? "Success" : "Fail") +
(error == null ? "" : "(" + error + ")");
}
}
}
| 2,360
| 29.269231
| 84
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/validator/DependentBlockHeaderRule.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.validator;
import org.ethereum.core.BlockHeader;
import org.slf4j.Logger;
import java.util.LinkedList;
import java.util.List;
/**
* Parent class for {@link BlockHeader} validators
* which run depends on the header of another block
*
* @author Mikhail Kalinin
* @since 02.09.2015
*/
public abstract class DependentBlockHeaderRule extends AbstractValidationRule {
protected List<String> errors = new LinkedList<>();
public List<String> getErrors() {
return errors;
}
public void logErrors(Logger logger) {
if (logger.isErrorEnabled())
for (String msg : errors) {
logger.warn("{} invalid: {}", getEntityClass().getSimpleName(), msg);
}
}
@Override
public Class getEntityClass() {
return BlockHeader.class;
}
/**
* Runs header validation and returns its result
*
* @param header block's header
* @param dependency header of the dependency block
* @return true if validation passed, false otherwise
*/
abstract public boolean validate(BlockHeader header, BlockHeader dependency);
}
| 1,937
| 29.761905
| 85
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/validator/GasLimitRule.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.validator;
import org.ethereum.config.SystemProperties;
import org.ethereum.config.Constants;
import org.ethereum.core.BlockHeader;
import java.math.BigInteger;
/**
* Checks {@link BlockHeader#gasLimit} against {@link Constants#getMIN_GAS_LIMIT}. <br>
*
* This check is NOT run in Frontier
*
* @author Mikhail Kalinin
* @since 02.09.2015
*/
public class GasLimitRule extends BlockHeaderRule {
private final int MIN_GAS_LIMIT;
public GasLimitRule(SystemProperties config) {
MIN_GAS_LIMIT = config.getBlockchainConfig().
getCommonConstants().getMIN_GAS_LIMIT();
}
@Override
public ValidationResult validate(BlockHeader header) {
if (new BigInteger(1, header.getGasLimit()).compareTo(BigInteger.valueOf(MIN_GAS_LIMIT)) < 0) {
return fault("header.getGasLimit() < MIN_GAS_LIMIT");
}
return Success;
}
}
| 1,709
| 31.264151
| 103
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/validator/ProofOfWorkRule.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.validator;
import org.ethereum.core.BlockHeader;
import org.ethereum.util.FastByteComparisons;
/**
* Checks proof value against its boundary for the block header
*
* @author Mikhail Kalinin
* @since 02.09.2015
*/
public class ProofOfWorkRule extends BlockHeaderRule {
@Override
public ValidationResult validate(BlockHeader header) {
byte[] proof = header.calcPowValue();
byte[] boundary = header.getPowBoundary();
if (!header.isGenesis() && FastByteComparisons.compareTo(proof, 0, 32, boundary, 0, 32) > 0) {
return fault(String.format("#%d: proofValue > header.getPowBoundary()", header.getNumber()));
}
return Success;
}
}
| 1,510
| 34.139535
| 105
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/validator/ParentNumberRule.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.validator;
import org.ethereum.core.BlockHeader;
/**
* Checks if {@link BlockHeader#number} == {@link BlockHeader#number} + 1 of parent's block
*
* @author Mikhail Kalinin
* @since 02.09.2015
*/
public class ParentNumberRule extends DependentBlockHeaderRule {
@Override
public boolean validate(BlockHeader header, BlockHeader parent) {
errors.clear();
if (header.getNumber() != (parent.getNumber() + 1)) {
errors.add(String.format("#%d: block number is not parentBlock number + 1", header.getNumber()));
return false;
}
return true;
}
}
| 1,427
| 32.209302
| 109
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/validator/BlockHashRule.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.validator;
import org.apache.commons.lang3.tuple.Pair;
import org.ethereum.config.BlockchainNetConfig;
import org.ethereum.config.SystemProperties;
import org.ethereum.core.BlockHeader;
import java.util.List;
/**
* Checks if the block is from the right fork
*/
public class BlockHashRule extends BlockHeaderRule {
private final BlockchainNetConfig blockchainConfig;
public BlockHashRule(SystemProperties config) {
blockchainConfig = config.getBlockchainConfig();
}
@Override
public ValidationResult validate(BlockHeader header) {
List<Pair<Long, BlockHeaderValidator>> validators = blockchainConfig.getConfigForBlock(header.getNumber()).headerValidators();
for (Pair<Long, BlockHeaderValidator> pair : validators) {
if (header.getNumber() == pair.getLeft()) {
ValidationResult result = pair.getRight().validate(header);
if (!result.success) {
return fault("Block " + header.getNumber() + " header constraint violated. " + result.error);
}
}
}
return Success;
}
}
| 1,942
| 35.660377
| 134
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/validator/BlockHeaderValidator.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.validator;
import org.ethereum.core.BlockHeader;
import java.util.Arrays;
import java.util.List;
/**
* Composite {@link BlockHeader} validator
* aggregating list of simple validation rules
*
* @author Mikhail Kalinin
* @since 02.09.2015
*/
public class BlockHeaderValidator extends BlockHeaderRule {
private List<BlockHeaderRule> rules;
public BlockHeaderValidator(List<BlockHeaderRule> rules) {
this.rules = rules;
}
public BlockHeaderValidator(BlockHeaderRule ...rules) {
this.rules = Arrays.asList(rules);
}
@Override
public ValidationResult validate(BlockHeader header) {
for (BlockHeaderRule rule : rules) {
ValidationResult result = rule.validate(header);
if (!result.success) {
return result;
}
}
return Success;
}
}
| 1,672
| 29.418182
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/validator/BlockCustomHashRule.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.validator;
import org.ethereum.core.BlockHeader;
import org.ethereum.util.FastByteComparisons;
import org.spongycastle.util.encoders.Hex;
/**
* Created by Stan Reshetnyk on 26.12.16.
*/
public class BlockCustomHashRule extends BlockHeaderRule {
public final byte[] blockHash;
public BlockCustomHashRule(byte[] blockHash) {
this.blockHash = blockHash;
}
@Override
public ValidationResult validate(BlockHeader header) {
if (!FastByteComparisons.equal(header.getHash(), blockHash)) {
return fault("Block " + header.getNumber() + " hash constraint violated. Expected:" +
Hex.toHexString(blockHash) + ", got: " + Hex.toHexString(header.getHash()));
}
return Success;
}
}
| 1,572
| 34.75
| 97
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/validator/ExtraDataPresenceRule.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.validator;
import org.ethereum.core.BlockHeader;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.FastByteComparisons;
import org.spongycastle.util.encoders.Hex;
/**
* Created by Stan Reshetnyk on 26.12.16.
*/
public class ExtraDataPresenceRule extends BlockHeaderRule {
public final byte[] data;
public final boolean required;
public ExtraDataPresenceRule(byte[] data, boolean required) {
this.data = data;
this.required = required;
}
@Override
public ValidationResult validate(BlockHeader header) {
final byte[] extraData = header.getExtraData() != null ? header.getExtraData() : ByteUtil.EMPTY_BYTE_ARRAY;
final boolean extraDataMatches = FastByteComparisons.equal(extraData, data);
if (required && !extraDataMatches) {
return fault("Block " + header.getNumber() + " is no-fork. Expected presence of: " +
Hex.toHexString(data) + ", in extra data: " + Hex.toHexString(extraData));
} else if (!required && extraDataMatches) {
return fault("Block " + header.getNumber() + " is pro-fork. Expected no: " +
Hex.toHexString(data) + ", in extra data: " + Hex.toHexString(extraData));
}
return Success;
}
}
| 2,088
| 37.685185
| 115
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/validator/BestNumberRule.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.validator;
import org.ethereum.config.Constants;
import org.ethereum.config.SystemProperties;
import org.ethereum.core.BlockHeader;
/**
* Checks diff between number of some block and number of our best block. <br>
* The diff must be more than -1 * {@link Constants#getBEST_NUMBER_DIFF_LIMIT}
*
* @author Mikhail Kalinin
* @since 02.09.2015
*/
public class BestNumberRule extends DependentBlockHeaderRule {
private final int BEST_NUMBER_DIFF_LIMIT;
public BestNumberRule(SystemProperties config) {
BEST_NUMBER_DIFF_LIMIT = config.getBlockchainConfig().
getCommonConstants().getBEST_NUMBER_DIFF_LIMIT();
}
@Override
public boolean validate(BlockHeader header, BlockHeader bestHeader) {
errors.clear();
long diff = header.getNumber() - bestHeader.getNumber();
if (diff > -1 * BEST_NUMBER_DIFF_LIMIT) {
errors.add(String.format(
"#%d: (header.getNumber() - bestHeader.getNumber()) <= BEST_NUMBER_DIFF_LIMIT",
header.getNumber()
));
return false;
}
return true;
}
}
| 1,951
| 32.655172
| 99
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/validator/EthashRule.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.validator;
import org.apache.commons.lang3.tuple.Pair;
import org.ethereum.config.SystemProperties;
import org.ethereum.core.BlockHeader;
import org.ethereum.core.BlockSummary;
import org.ethereum.listener.CompositeEthereumListener;
import org.ethereum.listener.EthereumListenerAdapter;
import org.ethereum.mine.EthashValidationHelper;
import org.ethereum.util.FastByteComparisons;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Random;
import static org.ethereum.validator.EthashRule.ChainType.main;
import static org.ethereum.validator.EthashRule.ChainType.reverse;
import static org.ethereum.validator.EthashRule.Mode.fake;
import static org.ethereum.validator.EthashRule.Mode.mixed;
/**
* Runs block header validation against Ethash dataset.
*
* <p>
* Configurable to work in several modes:
* <ul>
* <li> fake - partial checks without verification against Ethash dataset
* <li> strict - full check for each block
* <li> mixed - run full check for each block if main import flow during short sync,
* run full check in random fashion (<code>1/{@link #MIX_DENOMINATOR}</code> blocks are checked)
* during long sync, fast sync headers and blocks downloading
*
*
* @author Mikhail Kalinin
* @since 19.06.2018
*/
public class EthashRule extends BlockHeaderRule {
private static final Logger logger = LoggerFactory.getLogger("blockchain");
EthashValidationHelper ethashHelper;
ProofOfWorkRule powRule = new ProofOfWorkRule();
public enum Mode {
strict,
mixed,
fake;
static Mode parse(String name, Mode defaultMode) {
for (Mode mode : values()) {
if (mode.name().equals(name.toLowerCase()))
return mode;
}
return defaultMode;
}
}
public enum ChainType {
main, /** main chain, cache updates are stick to best block events, requires listener */
direct, /** side chain, cache is triggered each validation attempt, no listener required */
reverse; /** side chain with reverted validation order */
public boolean isSide() {
return this == reverse || this == direct;
}
}
private static final int MIX_DENOMINATOR = 5;
private Mode mode = mixed;
private ChainType chain = main;
private boolean syncDone = false;
private Random rnd = new Random();
// two most common settings
public static EthashRule createRegular(SystemProperties systemProperties, CompositeEthereumListener listener) {
return new EthashRule(Mode.parse(systemProperties.getEthashMode(), mixed), main, listener);
}
public static EthashRule createReverse(SystemProperties systemProperties) {
return new EthashRule(Mode.parse(systemProperties.getEthashMode(), mixed), reverse, null);
}
public EthashRule(Mode mode, ChainType chain, CompositeEthereumListener listener) {
this.mode = mode;
this.chain = chain;
if (this.mode != fake) {
this.ethashHelper = new EthashValidationHelper(
chain == reverse ? EthashValidationHelper.CacheOrder.reverse : EthashValidationHelper.CacheOrder.direct);
if (this.chain == main && listener != null) {
listener.addListener(new EthereumListenerAdapter() {
@Override
public void onSyncDone(SyncState state) {
EthashRule.this.syncDone = true;
}
@Override
public void onBlock(BlockSummary blockSummary, boolean best) {
if (best) ethashHelper.preCache(blockSummary.getBlock().getNumber());
}
});
}
}
}
@Override
public ValidationResult validate(BlockHeader header) {
if (header.isGenesis())
return Success;
if (ethashHelper == null)
return powRule.validate(header);
// trigger cache for side chains before mixed mode condition
if (chain.isSide())
ethashHelper.preCache(header.getNumber());
// mixed mode payload
if (mode == mixed && !syncDone && rnd.nextInt(100) % MIX_DENOMINATOR > 0)
return powRule.validate(header);
try {
Pair<byte[], byte[]> res = ethashHelper.ethashWorkFor(header, header.getNonce(), true);
// no cache for the epoch? fallback into fake rule
if (res == null) {
return powRule.validate(header);
}
if (!FastByteComparisons.equal(res.getLeft(), header.getMixHash())) {
return fault(String.format("#%d: mixHash doesn't match", header.getNumber()));
}
if (FastByteComparisons.compareTo(res.getRight(), 0, 32, header.getPowBoundary(), 0, 32) > 0) {
return fault(String.format("#%d: proofValue > header.getPowBoundary()", header.getNumber()));
}
return Success;
} catch (Exception e) {
logger.error("Failed to verify ethash work for block {}", header.getShortDescr(), e);
return fault("Failed to verify ethash work for block " + header.getShortDescr());
}
}
}
| 6,187
| 36.96319
| 125
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/validator/DependentBlockHeaderRuleAdapter.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.validator;
import org.ethereum.core.BlockHeader;
/**
* @author Mikhail Kalinin
* @since 25.09.2015
*/
public class DependentBlockHeaderRuleAdapter extends DependentBlockHeaderRule {
@Override
public boolean validate(BlockHeader header, BlockHeader dependency) {
return true;
}
}
| 1,116
| 32.848485
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/validator/AbstractValidationRule.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.validator;
/**
* Holds errors list to share between all rules
*
* @author Mikhail Kalinin
* @since 02.09.2015
*/
public abstract class AbstractValidationRule {
abstract public Class getEntityClass();
}
| 1,024
| 33.166667
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/validator/GasValueRule.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.validator;
import org.ethereum.core.BlockHeader;
import java.math.BigInteger;
/**
* Checks {@link BlockHeader#gasUsed} against {@link BlockHeader#gasLimit}
*
* @author Mikhail Kalinin
* @since 02.09.2015
*/
public class GasValueRule extends BlockHeaderRule {
@Override
public ValidationResult validate(BlockHeader header) {
if (new BigInteger(1, header.getGasLimit()).compareTo(BigInteger.valueOf(header.getGasUsed())) < 0) {
return fault("header.getGasLimit() < header.getGasUsed()");
}
return Success;
}
}
| 1,377
| 32.609756
| 109
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/validator/DifficultyRule.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.validator;
import org.ethereum.config.SystemProperties;
import org.ethereum.core.BlockHeader;
import java.math.BigInteger;
import static org.ethereum.util.BIUtil.isEqual;
/**
* Checks block's difficulty against calculated difficulty value
*
* @author Mikhail Kalinin
* @since 02.09.2015
*/
public class DifficultyRule extends DependentBlockHeaderRule {
private final SystemProperties config;
public DifficultyRule(SystemProperties config) {
this.config = config;
}
@Override
public boolean validate(BlockHeader header, BlockHeader parent) {
errors.clear();
BigInteger calcDifficulty = header.calcDifficulty(config.getBlockchainConfig(), parent);
BigInteger difficulty = header.getDifficultyBI();
if (!isEqual(difficulty, calcDifficulty)) {
errors.add(String.format("#%d: difficulty != calcDifficulty", header.getNumber()));
return false;
}
return true;
}
}
| 1,789
| 29.862069
| 96
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/validator/ParentGasLimitRule.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.validator;
import org.ethereum.config.SystemProperties;
import org.ethereum.core.BlockHeader;
import java.math.BigInteger;
/**
* Checks if {@link BlockHeader#gasLimit} matches gas limit bounds. <br>
*
* This check is NOT run in Frontier
*
* @author Mikhail Kalinin
* @since 02.09.2015
*/
public class ParentGasLimitRule extends DependentBlockHeaderRule {
private final int GAS_LIMIT_BOUND_DIVISOR;
public ParentGasLimitRule(SystemProperties config) {
GAS_LIMIT_BOUND_DIVISOR = config.getBlockchainConfig().
getCommonConstants().getGAS_LIMIT_BOUND_DIVISOR();
}
@Override
public boolean validate(BlockHeader header, BlockHeader parent) {
errors.clear();
BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit());
BigInteger parentGasLimit = new BigInteger(1, parent.getGasLimit());
if (headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(GAS_LIMIT_BOUND_DIVISOR - 1)).divide(BigInteger.valueOf(GAS_LIMIT_BOUND_DIVISOR))) < 0 ||
headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(GAS_LIMIT_BOUND_DIVISOR + 1)).divide(BigInteger.valueOf(GAS_LIMIT_BOUND_DIVISOR))) > 0) {
errors.add(String.format(
"#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR",
header.getNumber()
));
return false;
}
return true;
}
}
| 2,285
| 35.870968
| 169
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/PremineRaw.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core;
import java.math.BigInteger;
public class PremineRaw {
byte[] addr;
BigInteger value;
Denomination denomination;
public PremineRaw(byte[] addr, BigInteger value, Denomination denomination) {
this.addr = addr;
this.value = value;
this.denomination = denomination;
}
public byte[] getAddr() {
return addr;
}
public BigInteger getValue() {
return value;
}
public Denomination getDenomination() {
return denomination;
}
}
| 1,334
| 28.021739
| 81
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/ImportResult.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core;
public enum ImportResult {
IMPORTED_BEST,
IMPORTED_NOT_BEST,
EXIST,
NO_PARENT,
INVALID_BLOCK,
CONSENSUS_BREAK;
public boolean isSuccessful() {
return equals(IMPORTED_BEST) || equals(IMPORTED_NOT_BEST);
}
}
| 1,065
| 32.3125
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/BlockchainImpl.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core;
import org.apache.commons.lang3.tuple.Pair;
import org.ethereum.config.BlockchainConfig;
import org.ethereum.config.CommonConfig;
import org.ethereum.config.SystemProperties;
import org.ethereum.crypto.HashUtil;
import org.ethereum.datasource.inmem.HashMapDB;
import org.ethereum.db.*;
import org.ethereum.trie.Trie;
import org.ethereum.trie.TrieImpl;
import org.ethereum.listener.EthereumListener;
import org.ethereum.listener.EthereumListenerAdapter;
import org.ethereum.manager.AdminInfo;
import org.ethereum.sync.SyncManager;
import org.ethereum.util.*;
import org.ethereum.validator.DependentBlockHeaderRule;
import org.ethereum.validator.ParentBlockHeaderValidator;
import org.ethereum.vm.hook.VMHook;
import org.ethereum.vm.program.invoke.ProgramInvokeFactory;
import org.ethereum.vm.program.invoke.ProgramInvokeFactoryImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.Stack;
import static java.lang.Math.max;
import static java.lang.Runtime.getRuntime;
import static java.math.BigInteger.ONE;
import static java.math.BigInteger.ZERO;
import static java.util.Collections.emptyList;
import static org.ethereum.core.Denomination.SZABO;
import static org.ethereum.core.ImportResult.*;
import static org.ethereum.crypto.HashUtil.sha3;
import static org.ethereum.util.ByteUtil.toHexString;
/**
* The Ethereum blockchain is in many ways similar to the Bitcoin blockchain,
* although it does have some differences.
* <p>
* The main difference between Ethereum and Bitcoin with regard to the blockchain architecture
* is that, unlike Bitcoin, Ethereum blocks contain a copy of both the transaction list
* and the most recent state. Aside from that, two other values, the block number and
* the difficulty, are also stored in the block.
* </p>
* The block validation algorithm in Ethereum is as follows:
* <ol>
* <li>Check if the previous block referenced exists and is valid.</li>
* <li>Check that the timestamp of the block is greater than that of the referenced previous block and less than 15 minutes into the future</li>
* <li>Check that the block number, difficulty, transaction root, uncle root and gas limit (various low-level Ethereum-specific concepts) are valid.</li>
* <li>Check that the proof of work on the block is valid.</li>
* <li>Let S[0] be the STATE_ROOT of the previous block.</li>
* <li>Let TX be the block's transaction list, with n transactions.
* For all in in 0...n-1, set S[i+1] = APPLY(S[i],TX[i]).
* If any applications returns an error, or if the total gas consumed in the block
* up until this point exceeds the GASLIMIT, return an error.</li>
* <li>Let S_FINAL be S[n], but adding the block reward paid to the miner.</li>
* <li>Check if S_FINAL is the same as the STATE_ROOT. If it is, the block is valid; otherwise, it is not valid.</li>
* </ol>
* See <a href="https://github.com/ethereum/wiki/wiki/White-Paper#blockchain-and-mining">Ethereum Whitepaper</a>
*
* @author Roman Mandeleil
* @author Nick Savers
* @since 20.05.2014
*/
@Component
public class BlockchainImpl implements Blockchain, org.ethereum.facade.Blockchain {
private static final Logger logger = LoggerFactory.getLogger("blockchain");
private static final Logger stateLogger = LoggerFactory.getLogger("state");
// to avoid using minGasPrice=0 from Genesis for the wallet
private static final long INITIAL_MIN_GAS_PRICE = 10 * SZABO.longValue();
private static final int MAGIC_REWARD_OFFSET = 8;
public static final byte[] EMPTY_LIST_HASH = sha3(RLP.encodeList(new byte[0]));
@Autowired @Qualifier("defaultRepository")
private Repository repository;
@Autowired
protected BlockStore blockStore;
private HeaderStore headerStore = null;
@Autowired
private TransactionStore transactionStore;
private Block bestBlock;
private BigInteger totalDifficulty = ZERO;
@Autowired
private EthereumListener listener;
@Autowired
ProgramInvokeFactory programInvokeFactory;
@Autowired
private AdminInfo adminInfo;
@Autowired
private DependentBlockHeaderRule parentHeaderValidator;
@Autowired
private PendingState pendingState;
@Autowired
EventDispatchThread eventDispatchThread;
@Autowired
CommonConfig commonConfig = CommonConfig.getDefault();
@Autowired
SyncManager syncManager;
@Autowired
PruneManager pruneManager;
@Autowired
StateSource stateDataSource;
@Autowired
DbFlushManager dbFlushManager;
@Autowired
private VMHook vmHook;
SystemProperties config = SystemProperties.getDefault();
private List<Chain> altChains = new ArrayList<>();
private List<Block> garbage = new ArrayList<>();
long exitOn = Long.MAX_VALUE;
public boolean byTest = false;
private boolean fork = false;
private byte[] minerCoinbase;
private byte[] minerExtraData;
private int UNCLE_LIST_LIMIT;
private int UNCLE_GENERATION_LIMIT;
private Stack<State> stateStack = new Stack<>();
/** Tests only **/
public BlockchainImpl() {
}
@Autowired
public BlockchainImpl(final SystemProperties config) {
this.config = config;
initConst(config);
}
//todo: autowire over constructor
public BlockchainImpl(final BlockStore blockStore, final Repository repository) {
this.blockStore = blockStore;
this.repository = repository;
this.adminInfo = new AdminInfo();
this.listener = new EthereumListenerAdapter();
this.parentHeaderValidator = null;
this.transactionStore = new TransactionStore(new HashMapDB());
this.eventDispatchThread = EventDispatchThread.getDefault();
this.programInvokeFactory = new ProgramInvokeFactoryImpl();
initConst(SystemProperties.getDefault());
}
public BlockchainImpl withTransactionStore(TransactionStore transactionStore) {
this.transactionStore = transactionStore;
return this;
}
public BlockchainImpl withAdminInfo(AdminInfo adminInfo) {
this.adminInfo = adminInfo;
return this;
}
public BlockchainImpl withEthereumListener(EthereumListener listener) {
this.listener = listener;
return this;
}
public BlockchainImpl withSyncManager(SyncManager syncManager) {
this.syncManager = syncManager;
return this;
}
public BlockchainImpl withParentBlockHeaderValidator(ParentBlockHeaderValidator parentHeaderValidator) {
this.parentHeaderValidator = parentHeaderValidator;
return this;
}
public BlockchainImpl withVmHook(VMHook vmHook) {
this.vmHook = vmHook;
return this;
}
private void initConst(SystemProperties config) {
minerCoinbase = config.getMinerCoinbase();
minerExtraData = config.getMineExtraData();
UNCLE_LIST_LIMIT = config.getBlockchainConfig().getCommonConstants().getUNCLE_LIST_LIMIT();
UNCLE_GENERATION_LIMIT = config.getBlockchainConfig().getCommonConstants().getUNCLE_GENERATION_LIMIT();
}
@Override
public byte[] getBestBlockHash() {
return getBestBlock().getHash();
}
@Override
public long getSize() {
return bestBlock.getNumber() + 1;
}
@Override
public Block getBlockByNumber(long blockNr) {
return blockStore.getChainBlockByNumber(blockNr);
}
@Override
public TransactionInfo getTransactionInfo(byte[] hash) {
List<TransactionInfo> infos = transactionStore.get(hash);
if (infos == null || infos.isEmpty())
return null;
TransactionInfo txInfo = null;
if (infos.size() == 1) {
txInfo = infos.get(0);
} else {
// pick up the receipt from the block on the main chain
for (TransactionInfo info : infos) {
Block block = blockStore.getBlockByHash(info.blockHash);
Block mainBlock = blockStore.getChainBlockByNumber(block.getNumber());
if (FastByteComparisons.equal(info.blockHash, mainBlock.getHash())) {
txInfo = info;
break;
}
}
}
if (txInfo == null) {
logger.warn("Can't find block from main chain for transaction " + toHexString(hash));
return null;
}
Transaction tx = this.getBlockByHash(txInfo.getBlockHash()).getTransactionsList().get(txInfo.getIndex());
txInfo.setTransaction(tx);
return txInfo;
}
@Override
public Block getBlockByHash(byte[] hash) {
return blockStore.getBlockByHash(hash);
}
@Override
public synchronized List<byte[]> getListOfHashesStartFrom(byte[] hash, int qty) {
return blockStore.getListHashesEndWith(hash, qty);
}
@Override
public synchronized List<byte[]> getListOfHashesStartFromBlock(long blockNumber, int qty) {
long bestNumber = bestBlock.getNumber();
if (blockNumber > bestNumber) {
return emptyList();
}
if (blockNumber + qty - 1 > bestNumber) {
qty = (int) (bestNumber - blockNumber + 1);
}
long endNumber = blockNumber + qty - 1;
Block block = getBlockByNumber(endNumber);
List<byte[]> hashes = blockStore.getListHashesEndWith(block.getHash(), qty);
// asc order of hashes is required in the response
Collections.reverse(hashes);
return hashes;
}
public static byte[] calcTxTrie(List<Transaction> transactions) {
Trie txsState = new TrieImpl();
if (transactions == null || transactions.isEmpty())
return HashUtil.EMPTY_TRIE_HASH;
for (int i = 0; i < transactions.size(); i++) {
txsState.put(RLP.encodeInt(i), transactions.get(i).getEncoded());
}
return txsState.getRootHash();
}
public Repository getRepository() {
return repository;
}
public Repository getRepositorySnapshot() {
return repository.getSnapshotTo(blockStore.getBestBlock().getStateRoot());
}
@Override
public BlockStore getBlockStore() {
return blockStore;
}
public ProgramInvokeFactory getProgramInvokeFactory() {
return programInvokeFactory;
}
private State pushState(byte[] bestBlockHash) {
State push = stateStack.push(new State());
this.bestBlock = blockStore.getBlockByHash(bestBlockHash);
totalDifficulty = blockStore.getTotalDifficultyForHash(bestBlockHash);
this.repository = this.repository.getSnapshotTo(this.bestBlock.getStateRoot());
return push;
}
private void popState() {
State state = stateStack.pop();
this.repository = repository.getSnapshotTo(state.root);
this.bestBlock = state.savedBest;
this.totalDifficulty = state.savedTD;
}
public void dropState() {
stateStack.pop();
}
private synchronized BlockSummary tryConnectAndFork(final Block block) {
State savedState = pushState(block.getParentHash());
this.fork = true;
final BlockSummary summary;
Repository repo;
try {
// FIXME: adding block with no option for flush
Block parentBlock = getBlockByHash(block.getParentHash());
repo = repository.getSnapshotTo(parentBlock.getStateRoot());
summary = add(repo, block);
if (summary == null) {
return null;
}
} catch (Throwable th) {
logger.error("Unexpected error: ", th);
return null;
} finally {
this.fork = false;
}
if (summary.betterThan(savedState.savedTD)) {
logger.info("Rebranching: {} ~> {}", savedState.savedBest.getShortHash(), block.getShortHash());
// main branch become this branch
// cause we proved that total difficulty
// is greateer
blockStore.reBranch(block);
// The main repository rebranch
this.repository = repo;
// this.repository.syncToRoot(block.getStateRoot());
dropState();
} else {
// Stay on previous branch
popState();
}
return summary;
}
public synchronized ImportResult tryToConnect(final Block block) {
if (logger.isDebugEnabled())
logger.debug("Try connect block hash: {}, number: {}",
toHexString(block.getHash()).substring(0, 6),
block.getNumber());
if (blockStore.getMaxNumber() >= block.getNumber() &&
blockStore.isBlockExist(block.getHash())) {
if (logger.isDebugEnabled())
logger.debug("Block already exist hash: {}, number: {}",
toHexString(block.getHash()).substring(0, 6),
block.getNumber());
// retry of well known block
return EXIST;
}
final ImportResult ret;
// The simple case got the block
// to connect to the main chain
final BlockSummary summary;
if (bestBlock.isParentOf(block)) {
recordBlock(block);
// Repository repoSnap = repository.getSnapshotTo(bestBlock.getStateRoot());
summary = add(repository, block);
ret = summary == null ? INVALID_BLOCK : IMPORTED_BEST;
} else {
if (blockStore.isBlockExist(block.getParentHash())) {
BigInteger oldTotalDiff = getTotalDifficulty();
recordBlock(block);
summary = tryConnectAndFork(block);
ret = summary == null ? INVALID_BLOCK :
(summary.betterThan(oldTotalDiff) ? IMPORTED_BEST : IMPORTED_NOT_BEST);
} else {
summary = null;
ret = NO_PARENT;
}
}
if (ret.isSuccessful()) {
listener.onBlock(summary, ret == IMPORTED_BEST);
listener.trace(String.format("Block chain size: [ %d ]", this.getSize()));
if (ret == IMPORTED_BEST) {
eventDispatchThread.invokeLater(() -> pendingState.processBest(block, summary.getReceipts()));
}
}
return ret;
}
public synchronized Block createNewBlock(Block parent, List<Transaction> txs, List<BlockHeader> uncles) {
long time = System.currentTimeMillis() / 1000;
// adjust time to parent block this may happen due to system clocks difference
if (parent.getTimestamp() >= time) time = parent.getTimestamp() + 1;
return createNewBlock(parent, txs, uncles, time);
}
public synchronized Block createNewBlock(Block parent, List<Transaction> txs, List<BlockHeader> uncles, long time) {
final long blockNumber = parent.getNumber() + 1;
final byte[] extraData = config.getBlockchainConfig().getConfigForBlock(blockNumber).getExtraData(minerExtraData, blockNumber);
Block block = new Block(parent.getHash(),
EMPTY_LIST_HASH, // uncleHash
minerCoinbase,
new byte[0], // log bloom - from tx receipts
new byte[0], // difficulty computed right after block creation
blockNumber,
parent.getGasLimit(), // (add to config ?)
0, // gas used - computed after running all transactions
time, // block time
extraData, // extra data
new byte[0], // mixHash (to mine)
new byte[0], // nonce (to mine)
new byte[0], // receiptsRoot - computed after running all transactions
calcTxTrie(txs), // TransactionsRoot - computed after running all transactions
new byte[] {0}, // stateRoot - computed after running all transactions
txs,
null); // uncle list
for (BlockHeader uncle : uncles) {
block.addUncle(uncle);
}
block.getHeader().setDifficulty(ByteUtil.bigIntegerToBytes(block.getHeader().
calcDifficulty(config.getBlockchainConfig(), parent.getHeader())));
Repository track = repository.getSnapshotTo(parent.getStateRoot());
BlockSummary summary = applyBlock(track, block);
List<TransactionReceipt> receipts = summary.getReceipts();
block.setStateRoot(track.getRoot());
Bloom logBloom = new Bloom();
for (TransactionReceipt receipt : receipts) {
logBloom.or(receipt.getBloomFilter());
}
block.getHeader().setLogsBloom(logBloom.getData());
block.getHeader().setGasUsed(receipts.size() > 0 ? receipts.get(receipts.size() - 1).getCumulativeGasLong() : 0);
block.getHeader().setReceiptsRoot(calcReceiptsTrie(receipts));
return block;
}
@Override
public BlockSummary add(Block block) {
throw new RuntimeException("Not supported");
}
// @Override
public synchronized BlockSummary add(Repository repo, final Block block) {
BlockSummary summary = addImpl(repo, block);
if (summary == null) {
stateLogger.warn("Trying to reimport the block for debug...");
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
BlockSummary summary1 = addImpl(repo.getSnapshotTo(getBestBlock().getStateRoot()), block);
stateLogger.warn("Second import trial " + (summary1 == null ? "FAILED" : "OK"));
if (summary1 != null) {
if (config.exitOnBlockConflict() && !byTest) {
stateLogger.error("Inconsistent behavior, exiting...");
System.exit(-1);
} else {
return summary1;
}
}
}
return summary;
}
public synchronized BlockSummary addImpl(Repository repo, final Block block) {
if (exitOn < block.getNumber()) {
String msg = String.format("Exiting after block.number: %d", bestBlock.getNumber());
logger.info(msg);
System.out.println(msg);
dbFlushManager.flushSync();
System.exit(-1);
}
if (!isValid(repo, block)) {
logger.warn("Invalid block with number: {}", block.getNumber());
return null;
}
// Repository track = repo.startTracking();
byte[] origRoot = repo.getRoot();
if (block == null)
return null;
// keep chain continuity
// if (!Arrays.equals(bestBlock.getHash(),
// block.getParentHash())) return null;
if (block.getNumber() >= config.traceStartBlock() && config.traceStartBlock() != -1) {
AdvancedDeviceUtils.adjustDetailedTracing(config, block.getNumber());
}
BlockSummary summary = processBlock(repo, block);
final List<TransactionReceipt> receipts = summary.getReceipts();
// Sanity checks
if (!FastByteComparisons.equal(block.getReceiptsRoot(), calcReceiptsTrie(receipts))) {
logger.warn("Block's given Receipt Hash doesn't match: {} != {}", toHexString(block.getReceiptsRoot()), toHexString(calcReceiptsTrie(receipts)));
logger.warn("Calculated receipts: " + receipts);
repo.rollback();
summary = null;
}
if (!FastByteComparisons.equal(block.getLogBloom(), calcLogBloom(receipts))) {
logger.warn("Block's given logBloom Hash doesn't match: {} != {}", toHexString(block.getLogBloom()), toHexString(calcLogBloom(receipts)));
repo.rollback();
summary = null;
}
if (!FastByteComparisons.equal(block.getStateRoot(), repo.getRoot())) {
stateLogger.warn("BLOCK: State conflict or received invalid block. block: {} worldstate {} mismatch", block.getNumber(), toHexString(repo.getRoot()));
stateLogger.warn("Conflict block dump: {}", toHexString(block.getEncoded()));
// track.rollback();
// repository.rollback();
repository = repository.getSnapshotTo(origRoot);
// block is bad so 'rollback' the state root to the original state
// ((RepositoryImpl) repository).setRoot(origRoot);
// track.rollback();
// block is bad so 'rollback' the state root to the original state
// ((RepositoryImpl) repository).setRoot(origRoot);
if (config.exitOnBlockConflict() && !byTest) {
adminInfo.lostConsensus();
System.out.println("CONFLICT: BLOCK #" + block.getNumber() + ", dump: " + toHexString(block.getEncoded()));
System.exit(1);
} else {
summary = null;
}
}
if (summary != null) {
repo.commit();
updateTotalDifficulty(block);
summary.setTotalDifficulty(getTotalDifficulty());
if (!byTest) {
dbFlushManager.commit(() -> {
storeBlock(block, receipts);
repository.commit();
});
} else {
storeBlock(block, receipts);
}
}
return summary;
}
@Override
public void flush() {
// repository.flush();
// stateDataSource.flush();
// blockStore.flush();
// transactionStore.flush();
//
// repository = repository.getSnapshotTo(repository.getRoot());
//
// if (isMemoryBoundFlush()) {
// System.gc();
// }
}
private boolean needFlushByMemory(double maxMemoryPercents) {
return getRuntime().freeMemory() < (getRuntime().totalMemory() * (1 - maxMemoryPercents));
}
public static byte[] calcReceiptsTrie(List<TransactionReceipt> receipts) {
Trie receiptsTrie = new TrieImpl();
if (receipts == null || receipts.isEmpty())
return HashUtil.EMPTY_TRIE_HASH;
for (int i = 0; i < receipts.size(); i++) {
receiptsTrie.put(RLP.encodeInt(i), receipts.get(i).getReceiptTrieEncoded());
}
return receiptsTrie.getRootHash();
}
private byte[] calcLogBloom(List<TransactionReceipt> receipts) {
Bloom retBloomFilter = new Bloom();
if (receipts == null || receipts.isEmpty())
return retBloomFilter.getData();
for (TransactionReceipt receipt : receipts) {
retBloomFilter.or(receipt.getBloomFilter());
}
return retBloomFilter.getData();
}
public Block getParent(BlockHeader header) {
return blockStore.getBlockByHash(header.getParentHash());
}
public boolean isValid(BlockHeader header) {
if (parentHeaderValidator == null) return true;
Block parentBlock = getParent(header);
if (!parentHeaderValidator.validate(header, parentBlock.getHeader())) {
if (logger.isErrorEnabled())
parentHeaderValidator.logErrors(logger);
return false;
}
return true;
}
/**
* This mechanism enforces a homeostasis in terms of the time between blocks;
* a smaller period between the last two blocks results in an increase in the
* difficulty level and thus additional computation required, lengthening the
* likely next period. Conversely, if the period is too large, the difficulty,
* and expected time to the next block, is reduced.
*/
private boolean isValid(Repository repo, Block block) {
boolean isValid = true;
if (!block.isGenesis()) {
isValid = isValid(block.getHeader());
// Sanity checks
String trieHash = toHexString(block.getTxTrieRoot());
String trieListHash = toHexString(calcTxTrie(block.getTransactionsList()));
if (!trieHash.equals(trieListHash)) {
logger.warn("Block's given Trie Hash doesn't match: {} != {}", trieHash, trieListHash);
return false;
}
// if (!validateUncles(block)) return false;
List<Transaction> txs = block.getTransactionsList();
if (!txs.isEmpty()) {
// Repository parentRepo = repository;
// if (!Arrays.equals(bestBlock.getHash(), block.getParentHash())) {
// parentRepo = repository.getSnapshotTo(getBlockByHash(block.getParentHash()).getStateRoot());
// }
Map<ByteArrayWrapper, BigInteger> curNonce = new HashMap<>();
for (Transaction tx : txs) {
byte[] txSender = tx.getSender();
if (txSender == null) {
logger.warn("Invalid transaction: sender in tx with rlp={} is null." +
"Not valid until EIP-86", ByteUtil.toHexString(tx.getEncoded()));
return false;
}
ByteArrayWrapper key = new ByteArrayWrapper(txSender);
BigInteger expectedNonce = curNonce.get(key);
if (expectedNonce == null) {
expectedNonce = repo.getNonce(txSender);
}
curNonce.put(key, expectedNonce.add(ONE));
BigInteger txNonce = new BigInteger(1, tx.getNonce());
if (!expectedNonce.equals(txNonce)) {
logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}",
txNonce, expectedNonce, repo.getNonce(txSender), tx);
return false;
}
}
}
}
return isValid;
}
public boolean validateUncles(Block block) {
String unclesHash = toHexString(block.getHeader().getUnclesHash());
String unclesListHash = toHexString(HashUtil.sha3(block.getHeader().getUnclesEncoded(block.getUncleList())));
if (!unclesHash.equals(unclesListHash)) {
logger.warn("Block's given Uncle Hash doesn't match: {} != {}", unclesHash, unclesListHash);
return false;
}
if (block.getUncleList().size() > UNCLE_LIST_LIMIT) {
logger.warn("Uncle list to big: block.getUncleList().size() > UNCLE_LIST_LIMIT");
return false;
}
Set<ByteArrayWrapper> ancestors = getAncestors(blockStore, block, UNCLE_GENERATION_LIMIT + 1, false);
Set<ByteArrayWrapper> usedUncles = getUsedUncles(blockStore, block, false);
for (BlockHeader uncle : block.getUncleList()) {
// - They are valid headers (not necessarily valid blocks)
if (!isValid(uncle)) return false;
//if uncle's parent's number is not less than currentBlock - UNCLE_GEN_LIMIT, mark invalid
boolean isValid = !(getParent(uncle).getNumber() < (block.getNumber() - UNCLE_GENERATION_LIMIT));
if (!isValid) {
logger.warn("Uncle too old: generationGap must be under UNCLE_GENERATION_LIMIT");
return false;
}
ByteArrayWrapper uncleHash = new ByteArrayWrapper(uncle.getHash());
if (ancestors.contains(uncleHash)) {
logger.warn("Uncle is direct ancestor: " + toHexString(uncle.getHash()));
return false;
}
if (usedUncles.contains(uncleHash)) {
logger.warn("Uncle is not unique: " + toHexString(uncle.getHash()));
return false;
}
Block uncleParent = blockStore.getBlockByHash(uncle.getParentHash());
if (!ancestors.contains(new ByteArrayWrapper(uncleParent.getHash()))) {
logger.warn("Uncle has no common parent: " + toHexString(uncle.getHash()));
return false;
}
}
return true;
}
public static Set<ByteArrayWrapper> getAncestors(BlockStore blockStore, Block testedBlock, int limitNum, boolean isParentBlock) {
Set<ByteArrayWrapper> ret = new HashSet<>();
limitNum = (int) max(0, testedBlock.getNumber() - limitNum);
Block it = testedBlock;
if (!isParentBlock) {
it = blockStore.getBlockByHash(it.getParentHash());
}
while(it != null && it.getNumber() >= limitNum) {
ret.add(new ByteArrayWrapper(it.getHash()));
it = blockStore.getBlockByHash(it.getParentHash());
}
return ret;
}
public Set<ByteArrayWrapper> getUsedUncles(BlockStore blockStore, Block testedBlock, boolean isParentBlock) {
Set<ByteArrayWrapper> ret = new HashSet<>();
long limitNum = max(0, testedBlock.getNumber() - UNCLE_GENERATION_LIMIT);
Block it = testedBlock;
if (!isParentBlock) {
it = blockStore.getBlockByHash(it.getParentHash());
}
while(it.getNumber() > limitNum) {
for (BlockHeader uncle : it.getUncleList()) {
ret.add(new ByteArrayWrapper(uncle.getHash()));
}
it = blockStore.getBlockByHash(it.getParentHash());
}
return ret;
}
private BlockSummary processBlock(Repository track, Block block) {
if (!block.isGenesis() && !config.blockChainOnly()) {
return applyBlock(track, block);
}
else {
return new BlockSummary(block, new HashMap<byte[], BigInteger>(), new ArrayList<TransactionReceipt>(), new ArrayList<TransactionExecutionSummary>());
}
}
private BlockSummary applyBlock(Repository track, Block block) {
logger.debug("applyBlock: block: [{}] tx.list: [{}]", block.getNumber(), block.getTransactionsList().size());
BlockchainConfig blockchainConfig = config.getBlockchainConfig().getConfigForBlock(block.getNumber());
blockchainConfig.hardForkTransfers(block, track);
long saveTime = System.nanoTime();
int i = 1;
long totalGasUsed = 0;
List<TransactionReceipt> receipts = new ArrayList<>();
List<TransactionExecutionSummary> summaries = new ArrayList<>();
for (Transaction tx : block.getTransactionsList()) {
stateLogger.debug("apply block: [{}] tx: [{}] ", block.getNumber(), i);
Repository txTrack = track.startTracking();
TransactionExecutor executor = new TransactionExecutor(
tx, block.getCoinbase(),
txTrack, blockStore, programInvokeFactory, block, listener, totalGasUsed, vmHook)
.withCommonConfig(commonConfig);
executor.init();
executor.execute();
executor.go();
TransactionExecutionSummary summary = executor.finalization();
totalGasUsed += executor.getGasUsed();
txTrack.commit();
final TransactionReceipt receipt = executor.getReceipt();
if (blockchainConfig.eip658()) {
receipt.setTxStatus(receipt.isSuccessful());
} else {
receipt.setPostTxState(track.getRoot());
}
if (stateLogger.isInfoEnabled())
stateLogger.info("block: [{}] executed tx: [{}] \n state: [{}]", block.getNumber(), i,
toHexString(track.getRoot()));
stateLogger.info("[{}] ", receipt.toString());
if (stateLogger.isInfoEnabled())
stateLogger.info("tx[{}].receipt: [{}] ", i, toHexString(receipt.getEncoded()));
// TODO
// if (block.getNumber() >= config.traceStartBlock())
// repository.dumpState(block, totalGasUsed, i++, tx.getHash());
receipts.add(receipt);
if (summary != null) {
summaries.add(summary);
}
}
Map<byte[], BigInteger> rewards = addReward(track, block, summaries);
if (stateLogger.isInfoEnabled())
stateLogger.info("applied reward for block: [{}] \n state: [{}]",
block.getNumber(),
toHexString(track.getRoot()));
// TODO
// if (block.getNumber() >= config.traceStartBlock())
// repository.dumpState(block, totalGasUsed, 0, null);
long totalTime = System.nanoTime() - saveTime;
adminInfo.addBlockExecTime(totalTime);
logger.debug("block: num: [{}] hash: [{}], executed after: [{}]nano", block.getNumber(), block.getShortHash(), totalTime);
return new BlockSummary(block, rewards, receipts, summaries);
}
/**
* Add reward to block- and every uncle coinbase
* assuming the entire block is valid.
*
* @param block object containing the header and uncles
*/
private Map<byte[], BigInteger> addReward(Repository track, Block block, List<TransactionExecutionSummary> summaries) {
Map<byte[], BigInteger> rewards = new HashMap<>();
BigInteger blockReward = config.getBlockchainConfig().getConfigForBlock(block.getNumber()).getConstants().getBLOCK_REWARD();
BigInteger inclusionReward = blockReward.divide(BigInteger.valueOf(32));
// Add extra rewards based on number of uncles
if (block.getUncleList().size() > 0) {
for (BlockHeader uncle : block.getUncleList()) {
BigInteger uncleReward = blockReward
.multiply(BigInteger.valueOf(MAGIC_REWARD_OFFSET + uncle.getNumber() - block.getNumber()))
.divide(BigInteger.valueOf(MAGIC_REWARD_OFFSET));
track.addBalance(uncle.getCoinbase(),uncleReward);
BigInteger existingUncleReward = rewards.get(uncle.getCoinbase());
if (existingUncleReward == null) {
rewards.put(uncle.getCoinbase(), uncleReward);
} else {
rewards.put(uncle.getCoinbase(), existingUncleReward.add(uncleReward));
}
}
}
BigInteger minerReward = blockReward.add(inclusionReward.multiply(BigInteger.valueOf(block.getUncleList().size())));
BigInteger totalFees = BigInteger.ZERO;
for (TransactionExecutionSummary summary : summaries) {
totalFees = totalFees.add(summary.getFee());
}
rewards.put(block.getCoinbase(), minerReward.add(totalFees));
track.addBalance(block.getCoinbase(), minerReward); // fees are already given to the miner during tx execution
return rewards;
}
@Override
public synchronized void storeBlock(Block block, List<TransactionReceipt> receipts) {
if (fork)
blockStore.saveBlock(block, totalDifficulty, false);
else
blockStore.saveBlock(block, totalDifficulty, true);
for (int i = 0; i < receipts.size(); i++) {
transactionStore.put(new TransactionInfo(receipts.get(i), block.getHash(), i));
}
if (pruneManager != null) {
pruneManager.blockCommitted(block.getHeader());
}
logger.debug("Block saved: number: {}, hash: {}, TD: {}",
block.getNumber(), block.getShortHash(), totalDifficulty);
setBestBlock(block);
if (logger.isDebugEnabled())
logger.debug("block added to the blockChain: index: [{}]", block.getNumber());
if (block.getNumber() % 100 == 0)
logger.info("*** Last block added [ #{} ]", block.getNumber());
}
public boolean hasParentOnTheChain(Block block) {
return getParent(block.getHeader()) != null;
}
@Override
public List<Chain> getAltChains() {
return altChains;
}
@Override
public List<Block> getGarbage() {
return garbage;
}
public TransactionStore getTransactionStore() {
return transactionStore;
}
@Override
public void setBestBlock(Block block) {
bestBlock = block;
repository = repository.getSnapshotTo(block.getStateRoot());
}
@Override
public synchronized Block getBestBlock() {
// the method is synchronized since the bestBlock might be
// temporarily switched to the fork while importing non-best block
return bestBlock;
}
@Override
public synchronized void close() {
blockStore.close();
}
@Override
public BigInteger getTotalDifficulty() {
return totalDifficulty;
}
@Override
public synchronized void updateTotalDifficulty(Block block) {
totalDifficulty = totalDifficulty.add(block.getDifficultyBI());
logger.debug("TD: updated to {}", totalDifficulty);
}
@Override
public void setTotalDifficulty(BigInteger totalDifficulty) {
this.totalDifficulty = totalDifficulty;
}
private void recordBlock(Block block) {
if (!config.recordBlocks()) return;
String dumpDir = config.databaseDir() + "/" + config.dumpDir();
File dumpFile = new File(dumpDir + "/blocks-rec.dmp");
FileWriter fw = null;
BufferedWriter bw = null;
try {
dumpFile.getParentFile().mkdirs();
if (!dumpFile.exists()) dumpFile.createNewFile();
fw = new FileWriter(dumpFile.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
if (bestBlock.isGenesis()) {
bw.write(Hex.toHexString(bestBlock.getEncoded()));
bw.write("\n");
}
bw.write(Hex.toHexString(block.getEncoded()));
bw.write("\n");
} catch (IOException e) {
logger.error(e.getMessage(), e);
} finally {
try {
if (bw != null) bw.close();
if (fw != null) fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void updateBlockTotDifficulties(long startFrom) {
// no synchronization here not to lock instance for long period
while(true) {
synchronized (this) {
((IndexedBlockStore) blockStore).updateTotDifficulties(startFrom);
if (startFrom == bestBlock.getNumber()) {
totalDifficulty = blockStore.getTotalDifficultyForHash(bestBlock.getHash());
}
if (startFrom == blockStore.getMaxNumber()) {
Block bestStoredBlock = bestBlock;
BigInteger maxTD = totalDifficulty;
// traverse blocks toward max known number to get the best block
for (long num = bestBlock.getNumber() + 1; num <= blockStore.getMaxNumber(); num++) {
List<Block> blocks = ((IndexedBlockStore) blockStore).getBlocksByNumber(num);
for (Block block : blocks) {
BigInteger td = blockStore.getTotalDifficultyForHash(block.getHash());
if (maxTD.compareTo(td) < 0) {
maxTD = td;
bestStoredBlock = block;
}
}
}
if (totalDifficulty.compareTo(maxTD) < 0) {
blockStore.reBranch(bestStoredBlock);
bestBlock = bestStoredBlock;
totalDifficulty = maxTD;
repository = repository.getSnapshotTo(bestBlock.getStateRoot());
logger.info("totDifficulties update: re-branch to block {}, totalDifficulty {}",
bestBlock.getHeader().getShortDescr(), totalDifficulty);
}
break;
}
startFrom++;
}
}
}
public void setRepository(Repository repository) {
this.repository = repository;
}
public void setProgramInvokeFactory(ProgramInvokeFactory factory) {
this.programInvokeFactory = factory;
}
public void setExitOn(long exitOn) {
this.exitOn = exitOn;
}
public void setMinerCoinbase(byte[] minerCoinbase) {
this.minerCoinbase = minerCoinbase;
}
@Override
public byte[] getMinerCoinbase() {
return minerCoinbase;
}
public void setMinerExtraData(byte[] minerExtraData) {
this.minerExtraData = minerExtraData;
}
public boolean isBlockExist(byte[] hash) {
return blockStore.isBlockExist(hash);
}
public void setParentHeaderValidator(DependentBlockHeaderRule parentHeaderValidator) {
this.parentHeaderValidator = parentHeaderValidator;
}
public void setPendingState(PendingState pendingState) {
this.pendingState = pendingState;
}
public PendingState getPendingState() {
return pendingState;
}
@Override
public List<BlockHeader> getListOfHeadersStartFrom(BlockIdentifier identifier, int skip, int limit, boolean reverse) {
List<BlockHeader> headers = new ArrayList<>();
Iterator<BlockHeader> iterator = getIteratorOfHeadersStartFrom(identifier, skip, limit, reverse);
while (iterator.hasNext()) {
headers.add(iterator.next());
}
return headers;
}
@Override
public Iterator<BlockHeader> getIteratorOfHeadersStartFrom(BlockIdentifier identifier, int skip, int limit, boolean reverse) {
// Identifying block header we'll move from
BlockHeader startHeader;
if (identifier.getHash() != null) {
startHeader = findHeaderByHash(identifier.getHash());
} else {
startHeader = findHeaderByNumber(identifier.getNumber());
}
// If nothing found or provided hash is not on main chain, return empty array
if (startHeader == null) {
return EmptyBlockHeadersIterator.INSTANCE;
}
if (identifier.getHash() != null) {
BlockHeader mainChainHeader = findHeaderByNumber(startHeader.getNumber());
if (!startHeader.equals(mainChainHeader)) return EmptyBlockHeadersIterator.INSTANCE;
}
return new BlockHeadersIterator(startHeader, skip, limit, reverse);
}
/**
* Searches block in blockStore, if it's not found there
* and headerStore is defined, searches blockHeader in it.
* @param number block number
* @return Block header
*/
private BlockHeader findHeaderByNumber(long number) {
Block block = blockStore.getChainBlockByNumber(number);
if (block == null) {
if (headerStore != null) {
return headerStore.getHeaderByNumber(number);
} else {
return null;
}
} else {
return block.getHeader();
}
}
/**
* Searches block in blockStore, if it's not found there
* and headerStore is defined, searches blockHeader in it.
* @param hash block hash
* @return Block header
*/
private BlockHeader findHeaderByHash(byte[] hash) {
Block block = blockStore.getBlockByHash(hash);
if (block == null) {
if (headerStore != null) {
return headerStore.getHeaderByHash(hash);
} else {
return null;
}
} else {
return block.getHeader();
}
}
static class EmptyBlockHeadersIterator implements Iterator<BlockHeader> {
final static EmptyBlockHeadersIterator INSTANCE = new EmptyBlockHeadersIterator();
@Override
public boolean hasNext() {
return false;
}
@Override
public BlockHeader next() {
throw new NoSuchElementException("Nothing left");
}
}
class BlockHeadersIterator implements Iterator<BlockHeader> {
private final BlockHeader startHeader;
private final int skip;
private final int limit;
private final boolean reverse;
private Integer position = 0;
private Pair<Integer, BlockHeader> cachedNext = null;
BlockHeadersIterator(BlockHeader startHeader, int skip, int limit, boolean reverse) {
this.startHeader = startHeader;
this.skip = skip;
this.limit = limit;
this.reverse = reverse;
}
@Override
public boolean hasNext() {
if (startHeader == null || position >= limit) {
return false;
}
if (position == 0) {
// First
cachedNext = Pair.of(0, startHeader);
return true;
} else if (cachedNext.getLeft().equals(position)) {
// Already cached
return true;
} else {
// Main logic
BlockHeader prevHeader = cachedNext.getRight();
long nextBlockNumber;
if (reverse) {
nextBlockNumber = prevHeader.getNumber() - 1 - skip;
} else {
nextBlockNumber = prevHeader.getNumber() + 1 + skip;
}
BlockHeader nextHeader = null;
if (nextBlockNumber >= 0 && nextBlockNumber <= blockStore.getBestBlock().getNumber()) {
nextHeader = findHeaderByNumber(nextBlockNumber);
}
if (nextHeader == null) {
return false;
} else {
cachedNext = Pair.of(position, nextHeader);
return true;
}
}
}
@Override
public BlockHeader next() {
if (!hasNext()) {
throw new NoSuchElementException("Nothing left");
}
if (cachedNext == null || !cachedNext.getLeft().equals(position)) {
throw new ConcurrentModificationException("Concurrent modification");
}
++position;
return cachedNext.getRight();
}
}
@Override
public List<byte[]> getListOfBodiesByHashes(List<byte[]> hashes) {
List<byte[]> bodies = new ArrayList<>(hashes.size());
for (byte[] hash : hashes) {
Block block = blockStore.getBlockByHash(hash);
if (block == null) break;
bodies.add(block.getEncodedBody());
}
return bodies;
}
@Override
public Iterator<byte[]> getIteratorOfBodiesByHashes(List<byte[]> hashes) {
return new BlockBodiesIterator(hashes);
}
class BlockBodiesIterator implements Iterator<byte[]> {
private final List<byte[]> hashes;
private Integer position = 0;
BlockBodiesIterator(List<byte[]> hashes) {
this.hashes = new ArrayList<>(hashes);
}
@Override
public boolean hasNext() {
return position < hashes.size() && blockStore.getBlockByHash(hashes.get(position)) != null;
}
@Override
public byte[] next() {
if (!hasNext()) {
throw new NoSuchElementException("Nothing left");
}
Block block = blockStore.getBlockByHash(hashes.get(position));
if (block == null) {
throw new NoSuchElementException("Nothing left");
}
++position;
return block.getEncodedBody();
}
}
private class State {
// Repository savedRepo = repository;
byte[] root = repository.getRoot();
Block savedBest = bestBlock;
BigInteger savedTD = totalDifficulty;
}
public void setPruneManager(PruneManager pruneManager) {
this.pruneManager = pruneManager;
}
public void setHeaderStore(HeaderStore headerStore) {
this.headerStore = headerStore;
}
}
| 49,546
| 34.114812
| 162
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/TransactionReceipt.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core;
import org.ethereum.datasource.MemSizeEstimator;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPElement;
import org.ethereum.util.RLPItem;
import org.ethereum.util.RLPList;
import org.ethereum.vm.LogInfo;
import org.spongycastle.util.BigIntegers;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import static org.apache.commons.lang3.ArrayUtils.nullToEmpty;
import static org.ethereum.datasource.MemSizeEstimator.ByteArrayEstimator;
import static org.ethereum.util.ByteUtil.EMPTY_BYTE_ARRAY;
import static org.ethereum.util.ByteUtil.toHexString;
/**
* The transaction receipt is a tuple of three items
* comprising the transaction, together with the post-transaction state,
* and the cumulative gas used in the block containing the transaction receipt
* as of immediately after the transaction has happened,
*/
public class TransactionReceipt {
private Transaction transaction;
private byte[] postTxState = EMPTY_BYTE_ARRAY;
private byte[] cumulativeGas = EMPTY_BYTE_ARRAY;
private Bloom bloomFilter = new Bloom();
private List<LogInfo> logInfoList = new ArrayList<>();
private byte[] gasUsed = EMPTY_BYTE_ARRAY;
private byte[] executionResult = EMPTY_BYTE_ARRAY;
private String error = "";
/* Tx Receipt in encoded form */
private byte[] rlpEncoded;
public TransactionReceipt() {
}
public TransactionReceipt(byte[] rlp) {
RLPList params = RLP.decode2(rlp);
RLPList receipt = (RLPList) params.get(0);
RLPItem postTxStateRLP = (RLPItem) receipt.get(0);
RLPItem cumulativeGasRLP = (RLPItem) receipt.get(1);
RLPItem bloomRLP = (RLPItem) receipt.get(2);
RLPList logs = (RLPList) receipt.get(3);
RLPItem gasUsedRLP = (RLPItem) receipt.get(4);
RLPItem result = (RLPItem) receipt.get(5);
postTxState = nullToEmpty(postTxStateRLP.getRLPData());
cumulativeGas = cumulativeGasRLP.getRLPData();
bloomFilter = new Bloom(bloomRLP.getRLPData());
gasUsed = gasUsedRLP.getRLPData();
executionResult = (executionResult = result.getRLPData()) == null ? EMPTY_BYTE_ARRAY : executionResult;
if (receipt.size() > 6) {
byte[] errBytes = receipt.get(6).getRLPData();
error = errBytes != null ? new String(errBytes, StandardCharsets.UTF_8) : "";
}
for (RLPElement log : logs) {
LogInfo logInfo = new LogInfo(log.getRLPData());
logInfoList.add(logInfo);
}
rlpEncoded = rlp;
}
public TransactionReceipt(byte[] postTxState, byte[] cumulativeGas,
Bloom bloomFilter, List<LogInfo> logInfoList) {
this.postTxState = postTxState;
this.cumulativeGas = cumulativeGas;
this.bloomFilter = bloomFilter;
this.logInfoList = logInfoList;
}
public TransactionReceipt(final RLPList rlpList) {
if (rlpList == null || rlpList.size() != 4)
throw new RuntimeException("Should provide RLPList with postTxState, cumulativeGas, bloomFilter, logInfoList");
this.postTxState = rlpList.get(0).getRLPData();
this.cumulativeGas = rlpList.get(1).getRLPData();
this.bloomFilter = new Bloom(rlpList.get(2).getRLPData());
List<LogInfo> logInfos = new ArrayList<>();
for (RLPElement logInfoEl: (RLPList) rlpList.get(3)) {
LogInfo logInfo = new LogInfo(logInfoEl.getRLPData());
logInfos.add(logInfo);
}
this.logInfoList = logInfos;
}
public byte[] getPostTxState() {
return postTxState;
}
public byte[] getCumulativeGas() {
return cumulativeGas;
}
public byte[] getGasUsed() {
return gasUsed;
}
public byte[] getExecutionResult() {
return executionResult;
}
public long getCumulativeGasLong() {
return new BigInteger(1, cumulativeGas).longValue();
}
public Bloom getBloomFilter() {
return bloomFilter;
}
public List<LogInfo> getLogInfoList() {
return logInfoList;
}
public boolean isValid() {
return ByteUtil.byteArrayToLong(gasUsed) > 0;
}
public boolean isSuccessful() {
return error.isEmpty();
}
public String getError() {
return error;
}
/**
* Used for Receipt trie hash calculation. Should contain only the following items encoded:
* [postTxState, cumulativeGas, bloomFilter, logInfoList]
*/
public byte[] getReceiptTrieEncoded() {
return getEncoded(true);
}
/**
* Used for serialization, contains all the receipt data encoded
*/
public byte[] getEncoded() {
if (rlpEncoded == null) {
rlpEncoded = getEncoded(false);
}
return rlpEncoded;
}
public byte[] getEncoded(boolean receiptTrie) {
byte[] postTxStateRLP = RLP.encodeElement(this.postTxState);
byte[] cumulativeGasRLP = RLP.encodeElement(this.cumulativeGas);
byte[] bloomRLP = RLP.encodeElement(this.bloomFilter.data);
final byte[] logInfoListRLP;
if (logInfoList != null) {
byte[][] logInfoListE = new byte[logInfoList.size()][];
int i = 0;
for (LogInfo logInfo : logInfoList) {
logInfoListE[i] = logInfo.getEncoded();
++i;
}
logInfoListRLP = RLP.encodeList(logInfoListE);
} else {
logInfoListRLP = RLP.encodeList();
}
return receiptTrie ?
RLP.encodeList(postTxStateRLP, cumulativeGasRLP, bloomRLP, logInfoListRLP):
RLP.encodeList(postTxStateRLP, cumulativeGasRLP, bloomRLP, logInfoListRLP,
RLP.encodeElement(gasUsed), RLP.encodeElement(executionResult),
RLP.encodeElement(error.getBytes(StandardCharsets.UTF_8)));
}
public void setPostTxState(byte[] postTxState) {
this.postTxState = postTxState;
rlpEncoded = null;
}
public void setTxStatus(boolean success) {
this.postTxState = success ? new byte[]{1} : new byte[0];
rlpEncoded = null;
}
public boolean hasTxStatus() {
return postTxState != null && postTxState.length <= 1;
}
public boolean isTxStatusOK() {
return postTxState != null && postTxState.length == 1 && postTxState[0] == 1;
}
public void setCumulativeGas(long cumulativeGas) {
this.cumulativeGas = BigIntegers.asUnsignedByteArray(BigInteger.valueOf(cumulativeGas));
rlpEncoded = null;
}
public void setCumulativeGas(byte[] cumulativeGas) {
this.cumulativeGas = cumulativeGas;
rlpEncoded = null;
}
public void setGasUsed(byte[] gasUsed) {
this.gasUsed = gasUsed;
rlpEncoded = null;
}
public void setGasUsed(long gasUsed) {
this.gasUsed = BigIntegers.asUnsignedByteArray(BigInteger.valueOf(gasUsed));
rlpEncoded = null;
}
public void setExecutionResult(byte[] executionResult) {
this.executionResult = executionResult;
rlpEncoded = null;
}
public void setError(String error) {
this.error = error == null ? "" : error;
}
public void setLogInfoList(List<LogInfo> logInfoList) {
if (logInfoList == null) return;
this.logInfoList = logInfoList;
for (LogInfo loginfo : logInfoList) {
bloomFilter.or(loginfo.getBloom());
}
rlpEncoded = null;
}
public void setTransaction(Transaction transaction) {
this.transaction = transaction;
}
public Transaction getTransaction() {
if (transaction == null) throw new NullPointerException("Transaction is not initialized. Use TransactionInfo and BlockStore to setup Transaction instance");
return transaction;
}
@Override
public String toString() {
// todo: fix that
return "TransactionReceipt[" +
"\n , " + (hasTxStatus() ? ("txStatus=" + (isTxStatusOK() ? "OK" : "FAILED"))
: ("postTxState=" + toHexString(postTxState))) +
"\n , cumulativeGas=" + toHexString(cumulativeGas) +
"\n , gasUsed=" + toHexString(gasUsed) +
"\n , error=" + error +
"\n , executionResult=" + toHexString(executionResult) +
"\n , bloom=" + bloomFilter.toString() +
"\n , logs=" + logInfoList +
']';
}
public long estimateMemSize() {
return MemEstimator.estimateSize(this);
}
public static final MemSizeEstimator<TransactionReceipt> MemEstimator = receipt -> {
if (receipt == null) {
return 0;
}
long logSize = receipt.logInfoList.stream().mapToLong(LogInfo.MemEstimator::estimateSize).sum() + 16;
return (receipt.transaction == null ? 0 : Transaction.MemEstimator.estimateSize(receipt.transaction)) +
(receipt.postTxState == EMPTY_BYTE_ARRAY ? 0 : ByteArrayEstimator.estimateSize(receipt.postTxState)) +
(receipt.cumulativeGas == EMPTY_BYTE_ARRAY ? 0 : ByteArrayEstimator.estimateSize(receipt.cumulativeGas)) +
(receipt.gasUsed == EMPTY_BYTE_ARRAY ? 0 : ByteArrayEstimator.estimateSize(receipt.gasUsed)) +
(receipt.executionResult == EMPTY_BYTE_ARRAY ? 0 : ByteArrayEstimator.estimateSize(receipt.executionResult)) +
ByteArrayEstimator.estimateSize(receipt.rlpEncoded) +
Bloom.MEM_SIZE +
receipt.error.getBytes().length + 40 +
logSize;
};
}
| 10,617
| 33.141479
| 164
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/BlockHeader.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core;
import org.ethereum.config.BlockchainNetConfig;
import org.ethereum.crypto.HashUtil;
import org.ethereum.util.*;
import org.spongycastle.util.Arrays;
import org.spongycastle.util.BigIntegers;
import org.spongycastle.util.encoders.Hex;
import java.math.BigInteger;
import java.util.List;
import static org.ethereum.crypto.HashUtil.EMPTY_LIST_HASH;
import static org.ethereum.crypto.HashUtil.EMPTY_TRIE_HASH;
import static org.ethereum.util.ByteUtil.toHexString;
/**
* Block header is a value object containing
* the basic information of a block
*/
public class BlockHeader {
public static final int NONCE_LENGTH = 8;
public static final int HASH_LENGTH = 32;
public static final int ADDRESS_LENGTH = 20;
public static final int MAX_HEADER_SIZE = 800;
/* The SHA3 256-bit hash of the parent block, in its entirety */
private byte[] parentHash;
/* The SHA3 256-bit hash of the uncles list portion of this block */
private byte[] unclesHash;
/* The 160-bit address to which all fees collected from the
* successful mining of this block be transferred; formally */
private byte[] coinbase;
/* The SHA3 256-bit hash of the root node of the state trie,
* after all transactions are executed and finalisations applied */
private byte[] stateRoot;
/* The SHA3 256-bit hash of the root node of the trie structure
* populated with each transaction in the transaction
* list portion, the trie is populate by [key, val] --> [rlp(index), rlp(tx_recipe)]
* of the block */
private byte[] txTrieRoot;
/* The SHA3 256-bit hash of the root node of the trie structure
* populated with each transaction recipe in the transaction recipes
* list portion, the trie is populate by [key, val] --> [rlp(index), rlp(tx_recipe)]
* of the block */
private byte[] receiptTrieRoot;
/* The Bloom filter composed from indexable information
* (logger address and log topics) contained in each log entry
* from the receipt of each transaction in the transactions list */
private byte[] logsBloom;
/* A scalar value corresponding to the difficulty level of this block.
* This can be calculated from the previous block’s difficulty level
* and the timestamp */
private byte[] difficulty;
/* A scalar value equal to the reasonable output of Unix's time()
* at this block's inception */
private long timestamp;
/* A scalar value equal to the number of ancestor blocks.
* The genesis block has a number of zero */
private long number;
/* A scalar value equal to the current limit of gas expenditure per block */
private byte[] gasLimit;
/* A scalar value equal to the total gas used in transactions in this block */
private long gasUsed;
private byte[] mixHash;
/* An arbitrary byte array containing data relevant to this block.
* With the exception of the genesis block, this must be 32 bytes or fewer */
private byte[] extraData;
/* A 256-bit hash which proves that a sufficient amount
* of computation has been carried out on this block */
private byte[] nonce;
private byte[] hashCache;
public BlockHeader(byte[] encoded) {
this((RLPList) RLP.decode2(encoded).get(0));
}
public BlockHeader(RLPList rlpHeader) {
this.parentHash = rlpHeader.get(0).getRLPData();
this.unclesHash = rlpHeader.get(1).getRLPData();
this.coinbase = rlpHeader.get(2).getRLPData();
this.stateRoot = rlpHeader.get(3).getRLPData();
this.txTrieRoot = rlpHeader.get(4).getRLPData();
if (this.txTrieRoot == null)
this.txTrieRoot = EMPTY_TRIE_HASH;
this.receiptTrieRoot = rlpHeader.get(5).getRLPData();
if (this.receiptTrieRoot == null)
this.receiptTrieRoot = EMPTY_TRIE_HASH;
this.logsBloom = rlpHeader.get(6).getRLPData();
this.difficulty = rlpHeader.get(7).getRLPData();
byte[] nrBytes = rlpHeader.get(8).getRLPData();
byte[] glBytes = rlpHeader.get(9).getRLPData();
byte[] guBytes = rlpHeader.get(10).getRLPData();
byte[] tsBytes = rlpHeader.get(11).getRLPData();
this.number = ByteUtil.byteArrayToLong(nrBytes);
this.gasLimit = glBytes;
this.gasUsed = ByteUtil.byteArrayToLong(guBytes);
this.timestamp = ByteUtil.byteArrayToLong(tsBytes);
this.extraData = rlpHeader.get(12).getRLPData();
this.mixHash = rlpHeader.get(13).getRLPData();
this.nonce = rlpHeader.get(14).getRLPData();
}
public BlockHeader(byte[] parentHash, byte[] unclesHash, byte[] coinbase,
byte[] logsBloom, byte[] difficulty, long number,
byte[] gasLimit, long gasUsed, long timestamp,
byte[] extraData, byte[] mixHash, byte[] nonce) {
this.parentHash = parentHash;
this.unclesHash = unclesHash;
this.coinbase = coinbase;
this.logsBloom = logsBloom;
this.difficulty = difficulty;
this.number = number;
this.gasLimit = gasLimit;
this.gasUsed = gasUsed;
this.timestamp = timestamp;
this.extraData = extraData;
this.mixHash = mixHash;
this.nonce = nonce;
this.stateRoot = EMPTY_TRIE_HASH;
}
public boolean isGenesis() {
return this.getNumber() == Genesis.NUMBER;
}
public byte[] getParentHash() {
return parentHash;
}
public byte[] getUnclesHash() {
return unclesHash;
}
public void setUnclesHash(byte[] unclesHash) {
this.unclesHash = unclesHash;
hashCache = null;
}
public byte[] getCoinbase() {
return coinbase;
}
public void setCoinbase(byte[] coinbase) {
this.coinbase = coinbase;
hashCache = null;
}
public byte[] getStateRoot() {
return stateRoot;
}
public void setStateRoot(byte[] stateRoot) {
this.stateRoot = stateRoot;
hashCache = null;
}
public byte[] getTxTrieRoot() {
return txTrieRoot;
}
public void setReceiptsRoot(byte[] receiptTrieRoot) {
this.receiptTrieRoot = receiptTrieRoot;
hashCache = null;
}
public byte[] getReceiptsRoot() {
return receiptTrieRoot;
}
public void setTransactionsRoot(byte[] stateRoot) {
this.txTrieRoot = stateRoot;
hashCache = null;
}
public byte[] getLogsBloom() {
return logsBloom;
}
public byte[] getDifficulty() {
return difficulty;
}
public BigInteger getDifficultyBI() {
return new BigInteger(1, difficulty);
}
public void setDifficulty(byte[] difficulty) {
this.difficulty = difficulty;
hashCache = null;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
hashCache = null;
}
public long getNumber() {
return number;
}
public void setNumber(long number) {
this.number = number;
hashCache = null;
}
public byte[] getGasLimit() {
return gasLimit;
}
public void setGasLimit(byte[] gasLimit) {
this.gasLimit = gasLimit;
hashCache = null;
}
public long getGasUsed() {
return gasUsed;
}
public void setGasUsed(long gasUsed) {
this.gasUsed = gasUsed;
hashCache = null;
}
public byte[] getMixHash() {
return mixHash;
}
public void setMixHash(byte[] mixHash) {
this.mixHash = mixHash;
hashCache = null;
}
public byte[] getExtraData() {
return extraData;
}
public byte[] getNonce() {
return nonce;
}
public void setNonce(byte[] nonce) {
this.nonce = nonce;
hashCache = null;
}
public void setLogsBloom(byte[] logsBloom) {
this.logsBloom = logsBloom;
hashCache = null;
}
public void setExtraData(byte[] extraData) {
this.extraData = extraData;
hashCache = null;
}
public byte[] getHash() {
if (hashCache == null) {
hashCache = HashUtil.sha3(getEncoded());
}
return hashCache;
}
public byte[] getEncoded() {
return this.getEncoded(true); // with nonce
}
public byte[] getEncodedWithoutNonce() {
return this.getEncoded(false);
}
public byte[] getEncoded(boolean withNonce) {
byte[] parentHash = RLP.encodeElement(this.parentHash);
byte[] unclesHash = RLP.encodeElement(this.unclesHash);
byte[] coinbase = RLP.encodeElement(this.coinbase);
byte[] stateRoot = RLP.encodeElement(this.stateRoot);
if (txTrieRoot == null) this.txTrieRoot = EMPTY_TRIE_HASH;
byte[] txTrieRoot = RLP.encodeElement(this.txTrieRoot);
if (receiptTrieRoot == null) this.receiptTrieRoot = EMPTY_TRIE_HASH;
byte[] receiptTrieRoot = RLP.encodeElement(this.receiptTrieRoot);
byte[] logsBloom = RLP.encodeElement(this.logsBloom);
byte[] difficulty = RLP.encodeBigInteger(new BigInteger(1, this.difficulty));
byte[] number = RLP.encodeBigInteger(BigInteger.valueOf(this.number));
byte[] gasLimit = RLP.encodeElement(this.gasLimit);
byte[] gasUsed = RLP.encodeBigInteger(BigInteger.valueOf(this.gasUsed));
byte[] timestamp = RLP.encodeBigInteger(BigInteger.valueOf(this.timestamp));
byte[] extraData = RLP.encodeElement(this.extraData);
if (withNonce) {
byte[] mixHash = RLP.encodeElement(this.mixHash);
byte[] nonce = RLP.encodeElement(this.nonce);
return RLP.encodeList(parentHash, unclesHash, coinbase,
stateRoot, txTrieRoot, receiptTrieRoot, logsBloom, difficulty, number,
gasLimit, gasUsed, timestamp, extraData, mixHash, nonce);
} else {
return RLP.encodeList(parentHash, unclesHash, coinbase,
stateRoot, txTrieRoot, receiptTrieRoot, logsBloom, difficulty, number,
gasLimit, gasUsed, timestamp, extraData);
}
}
public byte[] getUnclesEncoded(List<BlockHeader> uncleList) {
byte[][] unclesEncoded = new byte[uncleList.size()][];
int i = 0;
for (BlockHeader uncle : uncleList) {
unclesEncoded[i] = uncle.getEncoded();
++i;
}
return RLP.encodeList(unclesEncoded);
}
public byte[] getPowBoundary() {
return BigIntegers.asUnsignedByteArray(32, BigInteger.ONE.shiftLeft(256).divide(getDifficultyBI()));
}
public byte[] calcPowValue() {
// nonce bytes are expected in Little Endian order, reverting
byte[] nonceReverted = Arrays.reverse(nonce);
byte[] hashWithoutNonce = HashUtil.sha3(getEncodedWithoutNonce());
byte[] seed = Arrays.concatenate(hashWithoutNonce, nonceReverted);
byte[] seedHash = HashUtil.sha512(seed);
byte[] concat = Arrays.concatenate(seedHash, mixHash);
return HashUtil.sha3(concat);
}
public BigInteger calcDifficulty(BlockchainNetConfig config, BlockHeader parent) {
return config.getConfigForBlock(getNumber()).
calcDifficulty(this, parent);
}
public boolean hasUncles() {
return !FastByteComparisons.equal(unclesHash, EMPTY_LIST_HASH);
}
public String toString() {
return toStringWithSuffix("\n");
}
private String toStringWithSuffix(final String suffix) {
StringBuilder toStringBuff = new StringBuilder();
toStringBuff.append(" hash=").append(toHexString(getHash())).append(suffix);
toStringBuff.append(" parentHash=").append(toHexString(parentHash)).append(suffix);
toStringBuff.append(" unclesHash=").append(toHexString(unclesHash)).append(suffix);
toStringBuff.append(" coinbase=").append(toHexString(coinbase)).append(suffix);
toStringBuff.append(" stateRoot=").append(toHexString(stateRoot)).append(suffix);
toStringBuff.append(" txTrieHash=").append(toHexString(txTrieRoot)).append(suffix);
toStringBuff.append(" receiptsTrieHash=").append(toHexString(receiptTrieRoot)).append(suffix);
toStringBuff.append(" difficulty=").append(toHexString(difficulty)).append(suffix);
toStringBuff.append(" number=").append(number).append(suffix);
// toStringBuff.append(" gasLimit=").append(gasLimit).append(suffix);
toStringBuff.append(" gasLimit=").append(toHexString(gasLimit)).append(suffix);
toStringBuff.append(" gasUsed=").append(gasUsed).append(suffix);
toStringBuff.append(" timestamp=").append(timestamp).append(" (").append(Utils.longToDateTime(timestamp)).append(")").append(suffix);
toStringBuff.append(" extraData=").append(toHexString(extraData)).append(suffix);
toStringBuff.append(" mixHash=").append(toHexString(mixHash)).append(suffix);
toStringBuff.append(" nonce=").append(toHexString(nonce)).append(suffix);
return toStringBuff.toString();
}
public String toFlatString() {
return toStringWithSuffix("");
}
public String getShortDescr() {
return "#" + getNumber() + " (" + Hex.toHexString(getHash()).substring(0,6) + " <~ "
+ Hex.toHexString(getParentHash()).substring(0,6) + ")";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BlockHeader that = (BlockHeader) o;
return FastByteComparisons.equal(getHash(), that.getHash());
}
@Override
public int hashCode() {
return Arrays.hashCode(getHash());
}
}
| 14,671
| 33.360656
| 142
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/PendingState.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core;
import java.util.List;
/**
* @author Mikhail Kalinin
* @since 28.09.2015
*/
public interface PendingState extends org.ethereum.facade.PendingState {
/**
* Adds transactions received from the net to the list of wire transactions <br>
* Triggers an update of pending state
*
* @param transactions txs received from the net
* @return sublist of transactions with NEW_PENDING status
*/
List<Transaction> addPendingTransactions(List<Transaction> transactions);
/**
* Adds transaction to the list of pending state txs <br>
* For the moment this list is populated with txs sent by our peer only <br>
* Triggers an update of pending state
*
* @param tx transaction
*/
void addPendingTransaction(Transaction tx);
/**
* It should be called on each block imported as <b>BEST</b> <br>
* Does several things:
* <ul>
* <li>removes block's txs from pending state and wire lists</li>
* <li>removes outdated wire txs</li>
* <li>updates pending state</li>
* </ul>
*
* @param block block imported into blockchain as a <b>BEST</b> one
*/
void processBest(Block block, List<TransactionReceipt> receipts);
}
| 2,058
| 33.898305
| 84
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/BlockHeaderWrapper.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPElement;
import org.ethereum.util.RLPList;
import org.spongycastle.util.encoders.Hex;
import java.util.Arrays;
import java.util.List;
import static org.ethereum.util.ByteUtil.toHexString;
/**
* <p>Wraps {@link BlockHeader}</p>
* Adds some additional data
*
* @author Mikhail Kalinin
* @since 05.02.2016
*/
public class BlockHeaderWrapper {
private BlockHeader header;
private byte[] nodeId;
public BlockHeaderWrapper(BlockHeader header, byte[] nodeId) {
this.header = header;
this.nodeId = nodeId;
}
public BlockHeaderWrapper(byte[] bytes) {
parse(bytes);
}
public byte[] getBytes() {
byte[] headerBytes = header.getEncoded();
byte[] nodeIdBytes = RLP.encodeElement(nodeId);
return RLP.encodeList(headerBytes, nodeIdBytes);
}
private void parse(byte[] bytes) {
List<RLPElement> params = RLP.decode2(bytes);
List<RLPElement> wrapper = (RLPList) params.get(0);
byte[] headerBytes = wrapper.get(0).getRLPData();
this.header= new BlockHeader(headerBytes);
this.nodeId = wrapper.get(1).getRLPData();
}
public byte[] getNodeId() {
return nodeId;
}
public byte[] getHash() {
return header.getHash();
}
public long getNumber() {
return header.getNumber();
}
public BlockHeader getHeader() {
return header;
}
public String getHexStrShort() {
return Hex.toHexString(header.getHash()).substring(0, 6);
}
public boolean sentBy(byte[] nodeId) {
return Arrays.equals(this.nodeId, nodeId);
}
@Override
public String toString() {
return "BlockHeaderWrapper {" +
"header=" + header +
", nodeId=" + toHexString(nodeId) +
'}';
}
}
| 2,702
| 26.581633
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/AccountState.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core;
import org.ethereum.config.BlockchainConfig;
import org.ethereum.config.SystemProperties;
import org.ethereum.crypto.HashUtil;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.FastByteComparisons;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPList;
import java.math.BigInteger;
import static org.ethereum.crypto.HashUtil.*;
import static org.ethereum.util.FastByteComparisons.equal;
import static org.ethereum.util.ByteUtil.toHexString;
public class AccountState {
private byte[] rlpEncoded;
/* A value equal to the number of transactions sent
* from this address, or, in the case of contract accounts,
* the number of contract-creations made by this account */
private final BigInteger nonce;
/* A scalar value equal to the number of Wei owned by this address */
private final BigInteger balance;
/* A 256-bit hash of the root node of a trie structure
* that encodes the storage contents of the contract,
* itself a simple mapping between byte arrays of size 32.
* The hash is formally denoted σ[a] s .
*
* Since I typically wish to refer not to the trie’s root hash
* but to the underlying set of key/value pairs stored within,
* I define a convenient equivalence TRIE (σ[a] s ) ≡ σ[a] s .
* It shall be understood that σ[a] s is not a ‘physical’ member
* of the account and does not contribute to its later serialisation */
private final byte[] stateRoot;
/* The hash of the EVM code of this contract—this is the code
* that gets executed should this address receive a message call;
* it is immutable and thus, unlike all other fields, cannot be changed
* after construction. All such code fragments are contained in
* the state database under their corresponding hashes for later
* retrieval */
private final byte[] codeHash;
public AccountState(SystemProperties config) {
this(config.getBlockchainConfig().getCommonConstants().getInitialNonce(), BigInteger.ZERO);
}
public AccountState(BigInteger nonce, BigInteger balance) {
this(nonce, balance, EMPTY_TRIE_HASH, EMPTY_DATA_HASH);
}
public AccountState(BigInteger nonce, BigInteger balance, byte[] stateRoot, byte[] codeHash) {
this.nonce = nonce;
this.balance = balance;
this.stateRoot = stateRoot == EMPTY_TRIE_HASH || equal(stateRoot, EMPTY_TRIE_HASH) ? EMPTY_TRIE_HASH : stateRoot;
this.codeHash = codeHash == EMPTY_DATA_HASH || equal(codeHash, EMPTY_DATA_HASH) ? EMPTY_DATA_HASH : codeHash;
}
public AccountState(byte[] rlpData) {
this.rlpEncoded = rlpData;
RLPList items = (RLPList) RLP.decode2(rlpEncoded).get(0);
this.nonce = ByteUtil.bytesToBigInteger(items.get(0).getRLPData());
this.balance = ByteUtil.bytesToBigInteger(items.get(1).getRLPData());
this.stateRoot = items.get(2).getRLPData();
this.codeHash = items.get(3).getRLPData();
}
public BigInteger getNonce() {
return nonce;
}
public AccountState withNonce(BigInteger nonce) {
return new AccountState(nonce, balance, stateRoot, codeHash);
}
public byte[] getStateRoot() {
return stateRoot;
}
public AccountState withStateRoot(byte[] stateRoot) {
return new AccountState(nonce, balance, stateRoot, codeHash);
}
public AccountState withIncrementedNonce() {
return new AccountState(nonce.add(BigInteger.ONE), balance, stateRoot, codeHash);
}
public byte[] getCodeHash() {
return codeHash;
}
public AccountState withCodeHash(byte[] codeHash) {
return new AccountState(nonce, balance, stateRoot, codeHash);
}
public BigInteger getBalance() {
return balance;
}
public AccountState withBalanceIncrement(BigInteger value) {
return new AccountState(nonce, balance.add(value), stateRoot, codeHash);
}
public byte[] getEncoded() {
if (rlpEncoded == null) {
byte[] nonce = RLP.encodeBigInteger(this.nonce);
byte[] balance = RLP.encodeBigInteger(this.balance);
byte[] stateRoot = RLP.encodeElement(this.stateRoot);
byte[] codeHash = RLP.encodeElement(this.codeHash);
this.rlpEncoded = RLP.encodeList(nonce, balance, stateRoot, codeHash);
}
return rlpEncoded;
}
public boolean isContractExist(BlockchainConfig blockchainConfig) {
return !FastByteComparisons.equal(codeHash, EMPTY_DATA_HASH) ||
!blockchainConfig.getConstants().getInitialNonce().equals(nonce);
}
public boolean isEmpty() {
return FastByteComparisons.equal(codeHash, EMPTY_DATA_HASH) &&
BigInteger.ZERO.equals(balance) &&
BigInteger.ZERO.equals(nonce);
}
public String toString() {
String ret = " Nonce: " + this.getNonce().toString() + "\n" +
" Balance: " + getBalance() + "\n" +
" State Root: " + toHexString(this.getStateRoot()) + "\n" +
" Code Hash: " + toHexString(this.getCodeHash());
return ret;
}
}
| 5,986
| 36.892405
| 121
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/TransactionExecutor.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core;
import org.apache.commons.lang3.tuple.Pair;
import org.ethereum.config.BlockchainConfig;
import org.ethereum.config.CommonConfig;
import org.ethereum.config.SystemProperties;
import org.ethereum.db.BlockStore;
import org.ethereum.db.ContractDetails;
import org.ethereum.listener.EthereumListener;
import org.ethereum.listener.EthereumListenerAdapter;
import org.ethereum.util.ByteArraySet;
import org.ethereum.vm.*;
import org.ethereum.vm.hook.VMHook;
import org.ethereum.vm.program.Program;
import org.ethereum.vm.program.ProgramResult;
import org.ethereum.vm.program.invoke.ProgramInvoke;
import org.ethereum.vm.program.invoke.ProgramInvokeFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigInteger;
import java.util.List;
import static java.util.Objects.isNull;
import static org.apache.commons.lang3.ArrayUtils.getLength;
import static org.apache.commons.lang3.ArrayUtils.isEmpty;
import static org.ethereum.util.BIUtil.*;
import static org.ethereum.util.ByteUtil.EMPTY_BYTE_ARRAY;
import static org.ethereum.util.ByteUtil.toHexString;
import static org.ethereum.vm.VMUtils.saveProgramTraceFile;
import static org.ethereum.vm.VMUtils.zipAndEncode;
/**
* @author Roman Mandeleil
* @since 19.12.2014
*/
public class TransactionExecutor {
private static final Logger logger = LoggerFactory.getLogger("execute");
private static final Logger stateLogger = LoggerFactory.getLogger("state");
SystemProperties config;
CommonConfig commonConfig;
BlockchainConfig blockchainConfig;
private Transaction tx;
private Repository track;
private Repository cacheTrack;
private BlockStore blockStore;
private final long gasUsedInTheBlock;
private boolean readyToExecute = false;
private String execError;
private ProgramInvokeFactory programInvokeFactory;
private byte[] coinbase;
private TransactionReceipt receipt;
private ProgramResult result = new ProgramResult();
private Block currentBlock;
private final EthereumListener listener;
private VM vm;
private Program program;
PrecompiledContracts.PrecompiledContract precompiledContract;
BigInteger m_endGas = BigInteger.ZERO;
long basicTxCost = 0;
List<LogInfo> logs = null;
private ByteArraySet touchedAccounts = new ByteArraySet();
boolean localCall = false;
private final VMHook vmHook;
public TransactionExecutor(Transaction tx, byte[] coinbase, Repository track, BlockStore blockStore,
ProgramInvokeFactory programInvokeFactory, Block currentBlock) {
this(tx, coinbase, track, blockStore, programInvokeFactory, currentBlock, new EthereumListenerAdapter(), 0, VMHook.EMPTY);
}
public TransactionExecutor(Transaction tx, byte[] coinbase, Repository track, BlockStore blockStore,
ProgramInvokeFactory programInvokeFactory, Block currentBlock,
EthereumListener listener, long gasUsedInTheBlock) {
this(tx, coinbase,track, blockStore, programInvokeFactory, currentBlock, listener, gasUsedInTheBlock, VMHook.EMPTY);
}
public TransactionExecutor(Transaction tx, byte[] coinbase, Repository track, BlockStore blockStore,
ProgramInvokeFactory programInvokeFactory, Block currentBlock,
EthereumListener listener, long gasUsedInTheBlock, VMHook vmHook) {
this.tx = tx;
this.coinbase = coinbase;
this.track = track;
this.cacheTrack = track.startTracking();
this.blockStore = blockStore;
this.programInvokeFactory = programInvokeFactory;
this.currentBlock = currentBlock;
this.listener = listener;
this.gasUsedInTheBlock = gasUsedInTheBlock;
this.m_endGas = toBI(tx.getGasLimit());
this.vmHook = isNull(vmHook) ? VMHook.EMPTY : vmHook;
withCommonConfig(CommonConfig.getDefault());
}
public TransactionExecutor withCommonConfig(CommonConfig commonConfig) {
this.commonConfig = commonConfig;
this.config = commonConfig.systemProperties();
this.blockchainConfig = config.getBlockchainConfig().getConfigForBlock(currentBlock.getNumber());
return this;
}
private void execError(String err) {
logger.warn(err);
execError = err;
}
/**
* Do all the basic validation, if the executor
* will be ready to run the transaction at the end
* set readyToExecute = true
*/
public void init() {
basicTxCost = tx.transactionCost(config.getBlockchainConfig(), currentBlock);
if (localCall) {
readyToExecute = true;
return;
}
BigInteger txGasLimit = new BigInteger(1, tx.getGasLimit());
BigInteger curBlockGasLimit = new BigInteger(1, currentBlock.getGasLimit());
boolean cumulativeGasReached = txGasLimit.add(BigInteger.valueOf(gasUsedInTheBlock)).compareTo(curBlockGasLimit) > 0;
if (cumulativeGasReached) {
execError(String.format("Too much gas used in this block: Require: %s Got: %s", new BigInteger(1, currentBlock.getGasLimit()).longValue() - toBI(tx.getGasLimit()).longValue(), toBI(tx.getGasLimit()).longValue()));
return;
}
if (txGasLimit.compareTo(BigInteger.valueOf(basicTxCost)) < 0) {
execError(String.format("Not enough gas for transaction execution: Require: %s Got: %s", basicTxCost, txGasLimit));
return;
}
BigInteger reqNonce = track.getNonce(tx.getSender());
BigInteger txNonce = toBI(tx.getNonce());
if (isNotEqual(reqNonce, txNonce)) {
execError(String.format("Invalid nonce: required: %s , tx.nonce: %s", reqNonce, txNonce));
return;
}
BigInteger txGasCost = toBI(tx.getGasPrice()).multiply(txGasLimit);
BigInteger totalCost = toBI(tx.getValue()).add(txGasCost);
BigInteger senderBalance = track.getBalance(tx.getSender());
if (!isCovers(senderBalance, totalCost)) {
execError(String.format("Not enough cash: Require: %s, Sender cash: %s", totalCost, senderBalance));
return;
}
if (!blockchainConfig.acceptTransactionSignature(tx)) {
execError("Transaction signature not accepted: " + tx.getSignature());
return;
}
readyToExecute = true;
}
public void execute() {
if (!readyToExecute) return;
if (!localCall) {
track.increaseNonce(tx.getSender());
BigInteger txGasLimit = toBI(tx.getGasLimit());
BigInteger txGasCost = toBI(tx.getGasPrice()).multiply(txGasLimit);
track.addBalance(tx.getSender(), txGasCost.negate());
if (logger.isInfoEnabled())
logger.info("Paying: txGasCost: [{}], gasPrice: [{}], gasLimit: [{}]", txGasCost, toBI(tx.getGasPrice()), txGasLimit);
}
if (tx.isContractCreation()) {
create();
} else {
call();
}
}
private void call() {
if (!readyToExecute) return;
byte[] targetAddress = tx.getReceiveAddress();
precompiledContract = PrecompiledContracts.getContractForAddress(DataWord.of(targetAddress), blockchainConfig);
if (precompiledContract != null) {
long requiredGas = precompiledContract.getGasForData(tx.getData());
BigInteger spendingGas = BigInteger.valueOf(requiredGas).add(BigInteger.valueOf(basicTxCost));
if (!localCall && m_endGas.compareTo(spendingGas) < 0) {
// no refund
// no endowment
execError("Out of Gas calling precompiled contract 0x" + toHexString(targetAddress) +
", required: " + spendingGas + ", left: " + m_endGas);
m_endGas = BigInteger.ZERO;
return;
} else {
m_endGas = m_endGas.subtract(spendingGas);
// FIXME: save return for vm trace
Pair<Boolean, byte[]> out = precompiledContract.execute(tx.getData());
if (!out.getLeft()) {
execError("Error executing precompiled contract 0x" + toHexString(targetAddress));
m_endGas = BigInteger.ZERO;
return;
}
}
} else {
byte[] code = track.getCode(targetAddress);
if (isEmpty(code)) {
m_endGas = m_endGas.subtract(BigInteger.valueOf(basicTxCost));
result.spendGas(basicTxCost);
} else {
ProgramInvoke programInvoke =
programInvokeFactory.createProgramInvoke(tx, currentBlock, cacheTrack, track, blockStore);
this.vm = new VM(config, vmHook);
this.program = new Program(track.getCodeHash(targetAddress), code, programInvoke, tx, config, vmHook).withCommonConfig(commonConfig);
}
}
BigInteger endowment = toBI(tx.getValue());
transfer(cacheTrack, tx.getSender(), targetAddress, endowment);
touchedAccounts.add(targetAddress);
}
private void create() {
byte[] newContractAddress = tx.getContractAddress();
AccountState existingAddr = cacheTrack.getAccountState(newContractAddress);
if (existingAddr != null && existingAddr.isContractExist(blockchainConfig)) {
execError("Trying to create a contract with existing contract address: 0x" + toHexString(newContractAddress));
m_endGas = BigInteger.ZERO;
return;
}
//In case of hashing collisions (for TCK tests only), check for any balance before createAccount()
BigInteger oldBalance = track.getBalance(newContractAddress);
cacheTrack.createAccount(tx.getContractAddress());
cacheTrack.addBalance(newContractAddress, oldBalance);
if (blockchainConfig.eip161()) {
cacheTrack.increaseNonce(newContractAddress);
}
if (isEmpty(tx.getData())) {
m_endGas = m_endGas.subtract(BigInteger.valueOf(basicTxCost));
result.spendGas(basicTxCost);
} else {
Repository originalRepo = track;
// Some TCK tests have storage only addresses (no code, zero nonce etc) - impossible situation in the real network
// So, we should clean up it before reuse, but as tx not always goes successful, state should be correctly
// reverted in that case too
if (cacheTrack.hasContractDetails(newContractAddress)) {
originalRepo = track.clone();
originalRepo.delete(newContractAddress);
}
ProgramInvoke programInvoke = programInvokeFactory.createProgramInvoke(tx, currentBlock,
cacheTrack, originalRepo, blockStore);
this.vm = new VM(config, vmHook);
this.program = new Program(tx.getData(), programInvoke, tx, config, vmHook).withCommonConfig(commonConfig);
// reset storage if the contract with the same address already exists
// TCK test case only - normally this is near-impossible situation in the real network
ContractDetails contractDetails = program.getStorage().getContractDetails(newContractAddress);
contractDetails.deleteStorage();
}
BigInteger endowment = toBI(tx.getValue());
transfer(cacheTrack, tx.getSender(), newContractAddress, endowment);
touchedAccounts.add(newContractAddress);
}
public void go() {
if (!readyToExecute) return;
try {
if (vm != null) {
// Charge basic cost of the transaction
program.spendGas(tx.transactionCost(config.getBlockchainConfig(), currentBlock), "TRANSACTION COST");
if (config.playVM())
vm.play(program);
result = program.getResult();
m_endGas = toBI(tx.getGasLimit()).subtract(toBI(program.getResult().getGasUsed()));
if (tx.isContractCreation() && !result.isRevert()) {
int returnDataGasValue = getLength(program.getResult().getHReturn()) *
blockchainConfig.getGasCost().getCREATE_DATA();
if (m_endGas.compareTo(BigInteger.valueOf(returnDataGasValue)) < 0) {
// Not enough gas to return contract code
if (!blockchainConfig.getConstants().createEmptyContractOnOOG()) {
program.setRuntimeFailure(Program.Exception.notEnoughSpendingGas("No gas to return just created contract",
returnDataGasValue, program));
result = program.getResult();
}
result.setHReturn(EMPTY_BYTE_ARRAY);
} else if (getLength(result.getHReturn()) > blockchainConfig.getConstants().getMAX_CONTRACT_SZIE()) {
// Contract size too large
program.setRuntimeFailure(Program.Exception.notEnoughSpendingGas("Contract size too large: " + getLength(result.getHReturn()),
returnDataGasValue, program));
result = program.getResult();
result.setHReturn(EMPTY_BYTE_ARRAY);
} else {
// Contract successfully created
m_endGas = m_endGas.subtract(BigInteger.valueOf(returnDataGasValue));
cacheTrack.saveCode(tx.getContractAddress(), result.getHReturn());
}
}
String err = config.getBlockchainConfig().getConfigForBlock(currentBlock.getNumber()).
validateTransactionChanges(blockStore, currentBlock, tx, null);
if (err != null) {
program.setRuntimeFailure(new RuntimeException("Transaction changes validation failed: " + err));
}
if (result.getException() != null || result.isRevert()) {
result.getDeleteAccounts().clear();
result.getLogInfoList().clear();
result.resetFutureRefund();
rollback();
if (result.getException() != null) {
throw result.getException();
} else {
execError("REVERT opcode executed");
}
} else {
touchedAccounts.addAll(result.getTouchedAccounts());
cacheTrack.commit();
}
} else {
cacheTrack.commit();
}
} catch (Throwable e) {
// TODO: catch whatever they will throw on you !!!
// https://github.com/ethereum/cpp-ethereum/blob/develop/libethereum/Executive.cpp#L241
rollback();
m_endGas = BigInteger.ZERO;
execError(e.getMessage());
}
}
private void rollback() {
cacheTrack.rollback();
// remove touched account
touchedAccounts.remove(
tx.isContractCreation() ? tx.getContractAddress() : tx.getReceiveAddress());
}
public TransactionExecutionSummary finalization() {
if (!readyToExecute) return null;
TransactionExecutionSummary.Builder summaryBuilder = TransactionExecutionSummary.builderFor(tx)
.gasLeftover(m_endGas)
.logs(result.getLogInfoList())
.result(result.getHReturn());
if (result != null) {
// Accumulate refunds for suicides
result.addFutureRefund(result.getDeleteAccounts().size() * config.getBlockchainConfig().
getConfigForBlock(currentBlock.getNumber()).getGasCost().getSUICIDE_REFUND());
long gasRefund = Math.min(Math.max(0, result.getFutureRefund()), getGasUsed() / 2);
byte[] addr = tx.isContractCreation() ? tx.getContractAddress() : tx.getReceiveAddress();
m_endGas = m_endGas.add(BigInteger.valueOf(gasRefund));
summaryBuilder
.gasUsed(toBI(result.getGasUsed()))
.gasRefund(toBI(gasRefund))
.deletedAccounts(result.getDeleteAccounts())
.internalTransactions(result.getInternalTransactions());
ContractDetails contractDetails = track.getContractDetails(addr);
if (contractDetails != null) {
// TODO
// summaryBuilder.storageDiff(track.getContractDetails(addr).getStorage());
//
// if (program != null) {
// summaryBuilder.touchedStorage(contractDetails.getStorage(), program.getStorageDiff());
// }
}
if (result.getException() != null) {
summaryBuilder.markAsFailed();
}
}
TransactionExecutionSummary summary = summaryBuilder.build();
// Refund for gas leftover
track.addBalance(tx.getSender(), summary.getLeftover().add(summary.getRefund()));
logger.info("Pay total refund to sender: [{}], refund val: [{}]", toHexString(tx.getSender()), summary.getRefund());
// Transfer fees to miner
track.addBalance(coinbase, summary.getFee());
touchedAccounts.add(coinbase);
logger.info("Pay fees to miner: [{}], feesEarned: [{}]", toHexString(coinbase), summary.getFee());
if (result != null) {
logs = result.getLogInfoList();
// Traverse list of suicides
for (DataWord address : result.getDeleteAccounts()) {
track.delete(address.getLast20Bytes());
}
}
if (blockchainConfig.eip161()) {
for (byte[] acctAddr : touchedAccounts) {
AccountState state = track.getAccountState(acctAddr);
if (state != null && state.isEmpty()) {
track.delete(acctAddr);
}
}
}
listener.onTransactionExecuted(summary);
if (config.vmTrace() && program != null && result != null) {
String trace = program.getTrace()
.result(result.getHReturn())
.error(result.getException())
.toString();
if (config.vmTraceCompressed()) {
trace = zipAndEncode(trace);
}
String txHash = toHexString(tx.getHash());
saveProgramTraceFile(config, txHash, trace);
listener.onVMTraceCreated(txHash, trace);
}
return summary;
}
public TransactionExecutor setLocalCall(boolean localCall) {
this.localCall = localCall;
return this;
}
public TransactionReceipt getReceipt() {
if (receipt == null) {
receipt = new TransactionReceipt();
long totalGasUsed = gasUsedInTheBlock + getGasUsed();
receipt.setCumulativeGas(totalGasUsed);
receipt.setTransaction(tx);
receipt.setLogInfoList(getVMLogs());
receipt.setGasUsed(getGasUsed());
receipt.setExecutionResult(getResult().getHReturn());
receipt.setError(execError);
// receipt.setPostTxState(track.getRoot()); // TODO later when RepositoryTrack.getRoot() is implemented
}
return receipt;
}
public List<LogInfo> getVMLogs() {
return logs;
}
public ProgramResult getResult() {
return result;
}
public long getGasUsed() {
return toBI(tx.getGasLimit()).subtract(m_endGas).longValue();
}
}
| 20,713
| 38.530534
| 225
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/TransactionTouchedStorage.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.collections4.keyvalue.AbstractKeyValue;
import org.ethereum.vm.DataWord;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
public class TransactionTouchedStorage {
public static class Entry extends AbstractKeyValue<DataWord,DataWord> {
private boolean changed;
public Entry(DataWord key, DataWord value, boolean changed) {
super(key, value);
this.changed = changed;
}
public Entry() {
super(null, null);
}
@Override
protected DataWord setKey(DataWord key) {
return super.setKey(key);
}
@Override
protected DataWord setValue(DataWord value) {
return super.setValue(value);
}
public boolean isChanged() {
return changed;
}
public void setChanged(boolean changed) {
this.changed = changed;
}
}
private Map<DataWord, Entry> entries = new HashMap<>();
public TransactionTouchedStorage() {
}
@JsonCreator
public TransactionTouchedStorage(Collection<Entry> entries) {
for (Entry entry : entries) {
add(entry);
}
}
@JsonValue
public Collection<Entry> getEntries() {
return entries.values();
}
public Entry add(Entry entry) {
return entries.put(entry.getKey(), entry);
}
private Entry add(Map.Entry<DataWord, DataWord> entry, boolean changed) {
return add(new Entry(entry.getKey(), entry.getValue(), changed));
}
void addReading(Map<DataWord, DataWord> entries) {
if (MapUtils.isEmpty(entries)) return;
for (Map.Entry<DataWord, DataWord> entry : entries.entrySet()) {
if (!this.entries.containsKey(entry.getKey())) add(entry, false);
}
}
void addWriting(Map<DataWord, DataWord> entries) {
if (MapUtils.isEmpty(entries)) return;
for (Map.Entry<DataWord, DataWord> entry : entries.entrySet()) {
add(entry, true);
}
}
private Map<DataWord, DataWord> keyValues(Function<Entry, Boolean> filter) {
Map<DataWord, DataWord> result = new HashMap<>();
for (Entry entry : getEntries()) {
if (filter == null || filter.apply(entry)) {
result.put(entry.getKey(), entry.getValue());
}
}
return result;
}
public Map<DataWord, DataWord> getChanged() {
return keyValues(Entry::isChanged);
}
public Map<DataWord, DataWord> getReadOnly() {
return keyValues(entry -> !entry.isChanged());
}
public Map<DataWord, DataWord> getAll() {
return keyValues(null);
}
public int size() {
return entries.size();
}
public boolean isEmpty() {
return entries.isEmpty();
}
}
| 3,881
| 27.335766
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/Denomination.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core;
import java.math.BigInteger;
public enum Denomination {
WEI(newBigInt(0)),
SZABO(newBigInt(12)),
FINNEY(newBigInt(15)),
ETHER(newBigInt(18));
private BigInteger amount;
private Denomination(BigInteger value) {
this.amount = value;
}
public BigInteger value() {
return amount;
}
public long longValue() {
return value().longValue();
}
private static BigInteger newBigInt(int value) {
return BigInteger.valueOf(10).pow(value);
}
public static String toFriendlyString(BigInteger value) {
if (value.compareTo(ETHER.value()) == 1 || value.compareTo(ETHER.value()) == 0) {
return Float.toString(value.divide(ETHER.value()).floatValue()) + " ETHER";
}
else if(value.compareTo(FINNEY.value()) == 1 || value.compareTo(FINNEY.value()) == 0) {
return Float.toString(value.divide(FINNEY.value()).floatValue()) + " FINNEY";
}
else if(value.compareTo(SZABO.value()) == 1 || value.compareTo(SZABO.value()) == 0) {
return Float.toString(value.divide(SZABO.value()).floatValue()) + " SZABO";
}
else
return Float.toString(value.divide(WEI.value()).floatValue()) + " WEI";
}
}
| 2,084
| 33.180328
| 95
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/BlockWrapper.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core;
import org.ethereum.datasource.MemSizeEstimator;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPElement;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;
import static org.ethereum.util.TimeUtils.secondsToMillis;
/**
* <p> Wraps {@link Block} </p>
* Adds some additional data required by core during blocks processing
*
* @author Mikhail Kalinin
* @since 24.07.2015
*/
public class BlockWrapper {
private static final long SOLID_BLOCK_DURATION_THRESHOLD = secondsToMillis(60);
private Block block;
private long importFailedAt = 0;
private long receivedAt = 0;
private boolean newBlock;
private byte[] nodeId;
public BlockWrapper(Block block, byte[] nodeId) {
this(block, false, nodeId);
}
public BlockWrapper(Block block, boolean newBlock, byte[] nodeId) {
this.block = block;
this.newBlock = newBlock;
this.nodeId = nodeId;
}
public BlockWrapper(byte[] bytes) {
parse(bytes);
}
public Block getBlock() {
return block;
}
public boolean isNewBlock() {
return newBlock;
}
public boolean isSolidBlock() {
return !newBlock || timeSinceReceiving() > SOLID_BLOCK_DURATION_THRESHOLD;
}
public long getImportFailedAt() {
return importFailedAt;
}
public void setImportFailedAt(long importFailedAt) {
this.importFailedAt = importFailedAt;
}
public byte[] getHash() {
return block.getHash();
}
public long getNumber() {
return block.getNumber();
}
public byte[] getEncoded() {
return block.getEncoded();
}
public String getShortHash() {
return block.getShortHash();
}
public byte[] getParentHash() {
return block.getParentHash();
}
public long getReceivedAt() {
return receivedAt;
}
public void setReceivedAt(long receivedAt) {
this.receivedAt = receivedAt;
}
public byte[] getNodeId() {
return nodeId;
}
public boolean sentBy(byte[] nodeId) {
return Arrays.equals(this.nodeId, nodeId);
}
public boolean isEqual(BlockWrapper wrapper) {
return wrapper != null && block.isEqual(wrapper.getBlock());
}
public void importFailed() {
if (importFailedAt == 0) {
importFailedAt = System.currentTimeMillis();
}
}
public void resetImportFail() {
importFailedAt = 0;
}
public long timeSinceFail() {
if(importFailedAt == 0) {
return 0;
} else {
return System.currentTimeMillis() - importFailedAt;
}
}
public long timeSinceReceiving() {
return System.currentTimeMillis() - receivedAt;
}
public byte[] getBytes() {
byte[] blockBytes = block.getEncoded();
byte[] importFailedBytes = RLP.encodeBigInteger(BigInteger.valueOf(importFailedAt));
byte[] receivedAtBytes = RLP.encodeBigInteger(BigInteger.valueOf(receivedAt));
byte[] newBlockBytes = RLP.encodeByte((byte) (newBlock ? 1 : 0));
byte[] nodeIdBytes = RLP.encodeElement(nodeId);
return RLP.encodeList(blockBytes, importFailedBytes,
receivedAtBytes, newBlockBytes, nodeIdBytes);
}
private void parse(byte[] bytes) {
List<RLPElement> wrapper = RLP.unwrapList(bytes);
byte[] blockBytes = wrapper.get(0).getRLPData();
byte[] importFailedBytes = wrapper.get(1).getRLPData();
byte[] receivedAtBytes = wrapper.get(2).getRLPData();
byte[] newBlockBytes = wrapper.get(3).getRLPData();
this.block = new Block(blockBytes);
this.importFailedAt = ByteUtil.byteArrayToLong(importFailedBytes);
this.receivedAt = ByteUtil.byteArrayToLong(receivedAtBytes);
byte newBlock = newBlockBytes == null ? 0 : new BigInteger(1, newBlockBytes).byteValue();
this.newBlock = newBlock == 1;
this.nodeId = wrapper.get(4).getRLPData();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BlockWrapper wrapper = (BlockWrapper) o;
return block.isEqual(wrapper.block);
}
public long estimateMemSize() {
return MemEstimator.estimateSize(this);
}
public static final MemSizeEstimator<BlockWrapper> MemEstimator = wrapper ->
Block.MemEstimator.estimateSize(wrapper.block) +
MemSizeEstimator.ByteArrayEstimator.estimateSize(wrapper.nodeId) +
8 + 8 + 1 + // importFailedAt + receivedAt + newBlock
16; // Object header + ref
}
| 5,562
| 28.278947
| 97
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/Chain.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core;
import org.ethereum.db.ByteArrayWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Roman Mandeleil
* @since 09.11.2014
*/
public class Chain {
private static final Logger logger = LoggerFactory.getLogger("blockchain");
private List<Block> chain = new ArrayList<>();
private BigInteger totalDifficulty = BigInteger.ZERO;
private Map<ByteArrayWrapper, Block> index = new HashMap<>();
public boolean tryToConnect(Block block) {
if (chain.isEmpty()) {
add(block);
return true;
}
Block lastBlock = chain.get(chain.size() - 1);
if (lastBlock.isParentOf(block)) {
add(block);
return true;
}
return false;
}
public void add(Block block) {
logger.info("adding block to alt chain block.hash: [{}] ", block.getShortHash());
totalDifficulty = totalDifficulty.add(block.getDifficultyBI());
logger.info("total difficulty on alt chain is: [{}] ", totalDifficulty);
chain.add(block);
index.put(new ByteArrayWrapper(block.getHash()), block);
}
public Block get(int i) {
return chain.get(i);
}
public Block getLast() {
return chain.get(chain.size() - 1);
}
public BigInteger getTotalDifficulty() {
return totalDifficulty;
}
public void setTotalDifficulty(BigInteger totalDifficulty) {
this.totalDifficulty = totalDifficulty;
}
public boolean isParentOnTheChain(Block block) {
return (index.get(new ByteArrayWrapper(block.getParentHash())) != null);
}
public long getSize() {
return chain.size();
}
}
| 2,643
| 27.12766
| 89
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/PendingStateImpl.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core;
import static org.ethereum.listener.EthereumListener.PendingTransactionState.DROPPED;
import static org.ethereum.listener.EthereumListener.PendingTransactionState.INCLUDED;
import static org.ethereum.listener.EthereumListener.PendingTransactionState.NEW_PENDING;
import static org.ethereum.listener.EthereumListener.PendingTransactionState.PENDING;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import org.apache.commons.collections4.map.LRUMap;
import org.ethereum.config.CommonConfig;
import org.ethereum.config.SystemProperties;
import org.ethereum.db.BlockStore;
import org.ethereum.db.ByteArrayWrapper;
import org.ethereum.db.TransactionStore;
import org.ethereum.listener.EthereumListener;
import org.ethereum.listener.EthereumListener.PendingTransactionState;
import org.ethereum.listener.EthereumListenerAdapter;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.FastByteComparisons;
import org.ethereum.vm.program.invoke.ProgramInvokeFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static org.ethereum.util.ByteUtil.toHexString;
/**
* Keeps logic providing pending state management
*
* @author Mikhail Kalinin
* @since 28.09.2015
*/
@Component
public class PendingStateImpl implements PendingState {
public static class TransactionSortedSet extends TreeSet<Transaction> {
public TransactionSortedSet() {
super((tx1, tx2) -> {
long nonceDiff = ByteUtil.byteArrayToLong(tx1.getNonce()) -
ByteUtil.byteArrayToLong(tx2.getNonce());
if (nonceDiff != 0) {
return nonceDiff > 0 ? 1 : -1;
}
return FastByteComparisons.compareTo(tx1.getHash(), 0, 32, tx2.getHash(), 0, 32);
});
}
}
private static final Logger logger = LoggerFactory.getLogger("pending");
@Autowired
private SystemProperties config = SystemProperties.getDefault();
@Autowired
CommonConfig commonConfig = CommonConfig.getDefault();
@Autowired
private EthereumListener listener;
@Autowired
private BlockchainImpl blockchain;
@Autowired
private BlockStore blockStore;
@Autowired
private TransactionStore transactionStore;
@Autowired
private ProgramInvokeFactory programInvokeFactory;
// private Repository repository;
private final List<PendingTransaction> pendingTransactions = new ArrayList<>();
// to filter out the transactions we have already processed
// transactions could be sent by peers even if they were already included into blocks
private final Map<ByteArrayWrapper, Object> receivedTxs = new LRUMap<>(100000);
private final Object dummyObject = new Object();
private Repository pendingState;
private Block best = null;
@Autowired
public PendingStateImpl(final EthereumListener listener) {
this.listener = listener;
// this.repository = blockchain.getRepository();
}
public void init() {
this.pendingState = getOrigRepository().startTracking();
}
private Repository getOrigRepository() {
return blockchain.getRepositorySnapshot();
}
@Override
public synchronized Repository getRepository() {
if (pendingState == null) {
init();
}
return pendingState;
}
@Override
public synchronized List<Transaction> getPendingTransactions() {
List<Transaction> txs = new ArrayList<>();
for (PendingTransaction tx : pendingTransactions) {
txs.add(tx.getTransaction());
}
return txs;
}
public Block getBestBlock() {
if (best == null) {
best = blockchain.getBestBlock();
}
return best;
}
private boolean addNewTxIfNotExist(Transaction tx) {
return receivedTxs.put(new ByteArrayWrapper(tx.getHash()), dummyObject) == null;
}
@Override
public void addPendingTransaction(Transaction tx) {
addPendingTransactions(Collections.singletonList(tx));
}
@Override
public synchronized List<Transaction> addPendingTransactions(List<Transaction> transactions) {
int unknownTx = 0;
List<Transaction> newPending = new ArrayList<>();
for (Transaction tx : transactions) {
if (addNewTxIfNotExist(tx)) {
unknownTx++;
if (addPendingTransactionImpl(tx)) {
newPending.add(tx);
}
}
}
logger.debug("Wire transaction list added: total: {}, new: {}, valid (added to pending): {} (current #of known txs: {})",
transactions.size(), unknownTx, newPending, receivedTxs.size());
if (!newPending.isEmpty()) {
listener.onPendingTransactionsReceived(newPending);
listener.onPendingStateChanged(PendingStateImpl.this);
}
return newPending;
}
public synchronized void trackTransaction(Transaction tx) {
List<TransactionInfo> infos = transactionStore.get(tx.getHash());
if (!infos.isEmpty()) {
for (TransactionInfo info : infos) {
Block txBlock = blockStore.getBlockByHash(info.getBlockHash());
if (txBlock.isEqual(blockStore.getChainBlockByNumber(txBlock.getNumber()))) {
// transaction included to the block on main chain
info.getReceipt().setTransaction(tx);
fireTxUpdate(info.getReceipt(), INCLUDED, txBlock);
return;
}
}
}
addPendingTransaction(tx);
}
private void fireTxUpdate(TransactionReceipt txReceipt, PendingTransactionState state, Block block) {
if (logger.isDebugEnabled()) {
logger.debug(String.format("PendingTransactionUpdate: (Tot: %3s) %12s : %s %8s %s [%s]",
getPendingTransactions().size(),
state, toHexString(txReceipt.getTransaction().getSender()).substring(0, 8),
ByteUtil.byteArrayToLong(txReceipt.getTransaction().getNonce()),
block.getShortDescr(), txReceipt.getError()));
}
listener.onPendingTransactionUpdate(txReceipt, state, block);
}
/**
* Executes pending tx on the latest best block
* Fires pending state update
* @param tx Transaction
* @return True if transaction gets NEW_PENDING state, False if DROPPED
*/
private boolean addPendingTransactionImpl(final Transaction tx) {
TransactionReceipt newReceipt = new TransactionReceipt();
newReceipt.setTransaction(tx);
String err = validate(tx);
TransactionReceipt txReceipt;
if (err != null) {
txReceipt = createDroppedReceipt(tx, err);
} else {
txReceipt = executeTx(tx);
}
if (!txReceipt.isValid()) {
fireTxUpdate(txReceipt, DROPPED, getBestBlock());
} else {
pendingTransactions.add(new PendingTransaction(tx, getBestBlock().getNumber()));
fireTxUpdate(txReceipt, NEW_PENDING, getBestBlock());
}
return txReceipt.isValid();
}
private TransactionReceipt createDroppedReceipt(Transaction tx, String error) {
TransactionReceipt txReceipt = new TransactionReceipt();
txReceipt.setTransaction(tx);
txReceipt.setError(error);
return txReceipt;
}
// validations which are not performed within executeTx
private String validate(Transaction tx) {
try {
tx.verify();
} catch (Exception e) {
return String.format("Invalid transaction: %s", e.getMessage());
}
if (config.getMineMinGasPrice().compareTo(ByteUtil.bytesToBigInteger(tx.getGasPrice())) > 0) {
return "Too low gas price for transaction: " + ByteUtil.bytesToBigInteger(tx.getGasPrice());
}
return null;
}
private Block findCommonAncestor(Block b1, Block b2) {
while(!b1.isEqual(b2)) {
if (b1.getNumber() >= b2.getNumber()) {
b1 = blockchain.getBlockByHash(b1.getParentHash());
}
if (b1.getNumber() < b2.getNumber()) {
b2 = blockchain.getBlockByHash(b2.getParentHash());
}
if (b1 == null || b2 == null) {
// shouldn't happen
throw new RuntimeException("Pending state can't find common ancestor: one of blocks has a gap");
}
}
return b1;
}
@Override
public synchronized void processBest(Block newBlock, List<TransactionReceipt> receipts) {
if (getBestBlock() != null && !getBestBlock().isParentOf(newBlock)) {
// need to switch the state to another fork
Block commonAncestor = findCommonAncestor(getBestBlock(), newBlock);
if (logger.isDebugEnabled()) logger.debug("New best block from another fork: "
+ newBlock.getShortDescr() + ", old best: " + getBestBlock().getShortDescr()
+ ", ancestor: " + commonAncestor.getShortDescr());
// first return back the transactions from forked blocks
Block rollback = getBestBlock();
while(!rollback.isEqual(commonAncestor)) {
List<PendingTransaction> blockTxs = new ArrayList<>();
for (Transaction tx : rollback.getTransactionsList()) {
logger.trace("Returning transaction back to pending: " + tx);
blockTxs.add(new PendingTransaction(tx, commonAncestor.getNumber()));
}
pendingTransactions.addAll(0, blockTxs);
rollback = blockchain.getBlockByHash(rollback.getParentHash());
}
// rollback the state snapshot to the ancestor
pendingState = getOrigRepository().getSnapshotTo(commonAncestor.getStateRoot()).startTracking();
// next process blocks from new fork
Block main = newBlock;
List<Block> mainFork = new ArrayList<>();
while(!main.isEqual(commonAncestor)) {
mainFork.add(main);
main = blockchain.getBlockByHash(main.getParentHash());
}
// processing blocks from ancestor to new block
for (int i = mainFork.size() - 1; i >= 0; i--) {
processBestInternal(mainFork.get(i), null);
}
} else {
logger.debug("PendingStateImpl.processBest: " + newBlock.getShortDescr());
processBestInternal(newBlock, receipts);
}
best = newBlock;
updateState(newBlock);
listener.onPendingStateChanged(PendingStateImpl.this);
}
private void processBestInternal(Block block, List<TransactionReceipt> receipts) {
clearPending(block, receipts);
clearOutdated(block.getNumber());
}
private void clearOutdated(final long blockNumber) {
List<PendingTransaction> outdated = new ArrayList<>();
for (PendingTransaction tx : pendingTransactions) {
if (blockNumber - tx.getBlockNumber() > config.txOutdatedThreshold()) {
outdated.add(tx);
fireTxUpdate(createDroppedReceipt(tx.getTransaction(),
"Tx was not included into last " + config.txOutdatedThreshold() + " blocks"),
DROPPED, getBestBlock());
}
}
if (outdated.isEmpty()) return;
if (logger.isDebugEnabled())
for (PendingTransaction tx : outdated)
logger.trace(
"Clear outdated pending transaction, block.number: [{}] hash: [{}]",
tx.getBlockNumber(),
toHexString(tx.getHash())
);
pendingTransactions.removeAll(outdated);
}
private void clearPending(Block block, List<TransactionReceipt> receipts) {
for (int i = 0; i < block.getTransactionsList().size(); i++) {
Transaction tx = block.getTransactionsList().get(i);
PendingTransaction pend = new PendingTransaction(tx);
if (pendingTransactions.remove(pend)) {
try {
logger.trace("Clear pending transaction, hash: [{}]", toHexString(tx.getHash()));
TransactionReceipt receipt;
if (receipts != null) {
receipt = receipts.get(i);
} else {
TransactionInfo info = getTransactionInfo(tx.getHash(), block.getHash());
receipt = info.getReceipt();
}
fireTxUpdate(receipt, INCLUDED, block);
} catch (Exception e) {
logger.error("Exception creating onPendingTransactionUpdate (block: " + block.getShortDescr() + ", tx: " + i, e);
}
}
}
}
private TransactionInfo getTransactionInfo(byte[] txHash, byte[] blockHash) {
TransactionInfo info = transactionStore.get(txHash, blockHash);
Transaction tx = blockchain.getBlockByHash(info.getBlockHash()).getTransactionsList().get(info.getIndex());
info.getReceipt().setTransaction(tx);
return info;
}
private void updateState(Block block) {
pendingState = getOrigRepository().startTracking();
long t = System.nanoTime();
for (PendingTransaction tx : pendingTransactions) {
TransactionReceipt receipt = executeTx(tx.getTransaction());
fireTxUpdate(receipt, PENDING, block);
}
logger.debug("Successfully processed #{}, txs: {}, time: {}s", block.getNumber(), pendingTransactions.size(),
String.format("%.3f", (System.nanoTime() - t) / 1_000_000_000d));
}
private TransactionReceipt executeTx(Transaction tx) {
logger.trace("Apply pending state tx: {}", toHexString(tx.getHash()));
Block best = getBestBlock();
TransactionExecutor executor = new TransactionExecutor(
tx, best.getCoinbase(), getRepository(),
blockStore, programInvokeFactory, createFakePendingBlock())
.withCommonConfig(commonConfig);
executor.init();
executor.execute();
executor.go();
executor.finalization();
return executor.getReceipt();
}
private Block createFakePendingBlock() {
// creating fake lightweight calculated block with no hashes calculations
Block block = new Block(best.getHash(),
BlockchainImpl.EMPTY_LIST_HASH, // uncleHash
new byte[32],
new byte[32], // log bloom - from tx receipts
new byte[0], // difficulty computed right after block creation
best.getNumber() + 1,
ByteUtil.longToBytesNoLeadZeroes(Long.MAX_VALUE), // max Gas Limit
0, // gas used
best.getTimestamp() + 1, // block time
new byte[0], // extra data
new byte[0], // mixHash (to mine)
new byte[0], // nonce (to mine)
new byte[32], // receiptsRoot
new byte[32], // TransactionsRoot
new byte[32], // stateRoot
Collections.<Transaction>emptyList(), // tx list
Collections.<BlockHeader>emptyList()); // uncle list
return block;
}
@Autowired
public void setBlockchain(BlockchainImpl blockchain) {
this.blockchain = blockchain;
this.blockStore = blockchain.getBlockStore();
this.programInvokeFactory = blockchain.getProgramInvokeFactory();
this.transactionStore = blockchain.getTransactionStore();
}
}
| 16,925
| 36.2
| 133
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/Bloom.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core;
import org.ethereum.util.ByteUtil;
import java.util.Arrays;
import static org.ethereum.util.ByteUtil.toHexString;
/**
* See http://www.herongyang.com/Java/Bit-String-Set-Bit-to-Byte-Array.html.
*
* @author Roman Mandeleil
* @since 20.11.2014
*/
public class Bloom {
public static final long MEM_SIZE = 256 + 16;
final static int _8STEPS = 8;
final static int _3LOW_BITS = 7;
final static int ENSURE_BYTE = 255;
byte[] data = new byte[256];
public Bloom() {
}
public Bloom(byte[] data) {
this.data = data;
}
public static Bloom create(byte[] toBloom) {
int mov1 = (((toBloom[0] & ENSURE_BYTE) & (_3LOW_BITS)) << _8STEPS) + ((toBloom[1]) & ENSURE_BYTE);
int mov2 = (((toBloom[2] & ENSURE_BYTE) & (_3LOW_BITS)) << _8STEPS) + ((toBloom[3]) & ENSURE_BYTE);
int mov3 = (((toBloom[4] & ENSURE_BYTE) & (_3LOW_BITS)) << _8STEPS) + ((toBloom[5]) & ENSURE_BYTE);
byte[] data = new byte[256];
Bloom bloom = new Bloom(data);
ByteUtil.setBit(data, mov1, 1);
ByteUtil.setBit(data, mov2, 1);
ByteUtil.setBit(data, mov3, 1);
return bloom;
}
public void or(Bloom bloom) {
for (int i = 0; i < data.length; ++i) {
data[i] |= bloom.data[i];
}
}
public boolean matches(Bloom topicBloom) {
Bloom copy = copy();
copy.or(topicBloom);
return this.equals(copy);
}
public byte[] getData() {
return data;
}
public Bloom copy() {
return new Bloom(Arrays.copyOf(getData(), getData().length));
}
@Override
public String toString() {
return toHexString(data);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Bloom bloom = (Bloom) o;
return Arrays.equals(data, bloom.data);
}
@Override
public int hashCode() {
return data != null ? Arrays.hashCode(data) : 0;
}
}
| 2,870
| 25.583333
| 107
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/Genesis.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core;
import org.ethereum.config.SystemProperties;
import org.ethereum.db.ByteArrayWrapper;
import org.ethereum.util.ByteUtil;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
/**
* The genesis block is the first block in the chain and has fixed values according to
* the protocol specification. The genesis block is 13 items, and is specified thus:
* <p>
* ( zerohash_256 , SHA3 RLP () , zerohash_160 , stateRoot, 0, 2^22 , 0, 0, 1000000, 0, 0, 0, SHA3 (42) , (), () )
* <p>
* - Where zerohash_256 refers to the parent hash, a 256-bit hash which is all zeroes;
* - zerohash_160 refers to the coinbase address, a 160-bit hash which is all zeroes;
* - 2^22 refers to the difficulty;
* - 0 refers to the timestamp (the Unix epoch);
* - the transaction trie root and extradata are both 0, being equivalent to the empty byte array.
* - The sequences of both uncles and transactions are empty and represented by ().
* - SHA3 (42) refers to the SHA3 hash of a byte array of length one whose first and only byte is of value 42.
* - SHA3 RLP () value refers to the hash of the uncle lists in RLP, both empty lists.
* <p>
* See Yellow Paper: http://www.gavwood.com/Paper.pdf (Appendix I. Genesis Block)
*/
public class Genesis extends Block {
private Map<ByteArrayWrapper, PremineAccount> premine = new HashMap<>();
public static byte[] ZERO_HASH_2048 = new byte[256];
public static byte[] DIFFICULTY = BigInteger.valueOf(2).pow(17).toByteArray();
public static long NUMBER = 0;
private static Block instance;
public Genesis(byte[] parentHash, byte[] unclesHash, byte[] coinbase, byte[] logsBloom,
byte[] difficulty, long number, long gasLimit,
long gasUsed, long timestamp,
byte[] extraData, byte[] mixHash, byte[] nonce){
super(parentHash, unclesHash, coinbase, logsBloom, difficulty,
number, ByteUtil.longToBytesNoLeadZeroes(gasLimit), gasUsed, timestamp, extraData,
mixHash, nonce, null, null);
}
public static Block getInstance() {
return SystemProperties.getDefault().getGenesis();
}
public static Genesis getInstance(SystemProperties config) {
return config.getGenesis();
}
public Map<ByteArrayWrapper, PremineAccount> getPremine() {
return premine;
}
public void setPremine(Map<ByteArrayWrapper, PremineAccount> premine) {
this.premine = premine;
}
public void addPremine(ByteArrayWrapper address, AccountState accountState) {
premine.put(address, new PremineAccount(accountState));
}
public static void populateRepository(Repository repository, Genesis genesis) {
for (ByteArrayWrapper key : genesis.getPremine().keySet()) {
final Genesis.PremineAccount premineAccount = genesis.getPremine().get(key);
final AccountState accountState = premineAccount.accountState;
repository.createAccount(key.getData());
repository.setNonce(key.getData(), accountState.getNonce());
repository.addBalance(key.getData(), accountState.getBalance());
if (premineAccount.code != null) {
repository.saveCode(key.getData(), premineAccount.code);
}
}
}
/**
* Used to keep addition fields.
*/
public static class PremineAccount {
public byte[] code;
public AccountState accountState;
public byte[] getStateRoot() {
return accountState.getStateRoot();
}
public PremineAccount(AccountState accountState) {
this.accountState = accountState;
}
public PremineAccount() {
}
}
}
| 4,564
| 37.041667
| 114
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/PendingTransaction.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core;
import org.ethereum.util.ByteUtil;
import java.math.BigInteger;
import java.util.Arrays;
/**
* Decorates {@link Transaction} class with additional attributes
* related to Pending Transaction logic
*
* @author Mikhail Kalinin
* @since 11.08.2015
*/
public class PendingTransaction {
/**
* transaction
*/
private Transaction transaction;
/**
* number of block that was best at the moment when transaction's been added
*/
private long blockNumber;
public PendingTransaction(byte[] bytes) {
parse(bytes);
}
public PendingTransaction(Transaction transaction) {
this(transaction, 0);
}
public PendingTransaction(Transaction transaction, long blockNumber) {
this.transaction = transaction;
this.blockNumber = blockNumber;
}
public Transaction getTransaction() {
return transaction;
}
public long getBlockNumber() {
return blockNumber;
}
public byte[] getSender() {
return transaction.getSender();
}
public byte[] getHash() {
return transaction.getHash();
}
public byte[] getBytes() {
byte[] numberBytes = BigInteger.valueOf(blockNumber).toByteArray();
byte[] txBytes = transaction.getEncoded();
byte[] bytes = new byte[1 + numberBytes.length + txBytes.length];
bytes[0] = (byte) numberBytes.length;
System.arraycopy(numberBytes, 0, bytes, 1, numberBytes.length);
System.arraycopy(txBytes, 0, bytes, 1 + numberBytes.length, txBytes.length);
return bytes;
}
private void parse(byte[] bytes) {
byte[] numberBytes = new byte[bytes[0]];
byte[] txBytes = new byte[bytes.length - 1 - numberBytes.length];
System.arraycopy(bytes, 1, numberBytes, 0, numberBytes.length);
System.arraycopy(bytes, 1 + numberBytes.length, txBytes, 0, txBytes.length);
this.blockNumber = new BigInteger(numberBytes).longValue();
this.transaction = new Transaction(txBytes);
}
@Override
public String toString() {
return "PendingTransaction [" +
" transaction=" + transaction +
", blockNumber=" + blockNumber +
']';
}
/**
* Two pending transaction are equal if equal their sender + nonce
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof PendingTransaction)) return false;
PendingTransaction that = (PendingTransaction) o;
return Arrays.equals(getSender(), that.getSender()) &&
Arrays.equals(transaction.getNonce(), that.getTransaction().getNonce());
}
@Override
public int hashCode() {
return ByteUtil.byteArrayToInt(getSender()) + ByteUtil.byteArrayToInt(transaction.getNonce());
}
}
| 3,680
| 28.448
| 102
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/Block.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core;
import org.ethereum.crypto.HashUtil;
import org.ethereum.datasource.MemSizeEstimator;
import org.ethereum.trie.Trie;
import org.ethereum.trie.TrieImpl;
import org.ethereum.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.Arrays;
import org.spongycastle.util.encoders.Hex;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import static org.ethereum.crypto.HashUtil.sha3;
import static org.ethereum.datasource.MemSizeEstimator.ByteArrayEstimator;
import static org.ethereum.util.ByteUtil.toHexString;
/**
* The block in Ethereum is the collection of relevant pieces of information
* (known as the blockheader), H, together with information corresponding to
* the comprised transactions, R, and a set of other blockheaders U that are known
* to have a parent equal to the present block’s parent’s parent
* (such blocks are known as uncles).
*
* @author Roman Mandeleil
* @author Nick Savers
* @since 20.05.2014
*/
public class Block {
private static final Logger logger = LoggerFactory.getLogger("blockchain");
private BlockHeader header;
/* Transactions */
private List<Transaction> transactionsList = new CopyOnWriteArrayList<>();
/* Uncles */
private List<BlockHeader> uncleList = new CopyOnWriteArrayList<>();
/* Private */
private byte[] rlpEncoded;
private boolean parsed = false;
/* Constructors */
private Block() {
}
public Block(byte[] rawData) {
logger.debug("new from [" + toHexString(rawData) + "]");
this.rlpEncoded = rawData;
}
public Block(BlockHeader header, List<Transaction> transactionsList, List<BlockHeader> uncleList) {
this(header.getParentHash(),
header.getUnclesHash(),
header.getCoinbase(),
header.getLogsBloom(),
header.getDifficulty(),
header.getNumber(),
header.getGasLimit(),
header.getGasUsed(),
header.getTimestamp(),
header.getExtraData(),
header.getMixHash(),
header.getNonce(),
header.getReceiptsRoot(),
header.getTxTrieRoot(),
header.getStateRoot(),
transactionsList,
uncleList);
}
public Block(byte[] parentHash, byte[] unclesHash, byte[] coinbase, byte[] logsBloom,
byte[] difficulty, long number, byte[] gasLimit,
long gasUsed, long timestamp, byte[] extraData,
byte[] mixHash, byte[] nonce, byte[] receiptsRoot,
byte[] transactionsRoot, byte[] stateRoot,
List<Transaction> transactionsList, List<BlockHeader> uncleList) {
this(parentHash, unclesHash, coinbase, logsBloom, difficulty, number, gasLimit,
gasUsed, timestamp, extraData, mixHash, nonce, transactionsList, uncleList);
this.header.setTransactionsRoot(BlockchainImpl.calcTxTrie(transactionsList));
if (!Hex.toHexString(transactionsRoot).
equals(Hex.toHexString(this.header.getTxTrieRoot())))
logger.debug("Transaction root miss-calculate, block: {}", getNumber());
this.header.setStateRoot(stateRoot);
this.header.setReceiptsRoot(receiptsRoot);
}
public Block(byte[] parentHash, byte[] unclesHash, byte[] coinbase, byte[] logsBloom,
byte[] difficulty, long number, byte[] gasLimit,
long gasUsed, long timestamp,
byte[] extraData, byte[] mixHash, byte[] nonce,
List<Transaction> transactionsList, List<BlockHeader> uncleList) {
this.header = new BlockHeader(parentHash, unclesHash, coinbase, logsBloom,
difficulty, number, gasLimit, gasUsed,
timestamp, extraData, mixHash, nonce);
this.transactionsList = transactionsList;
if (this.transactionsList == null) {
this.transactionsList = new CopyOnWriteArrayList<>();
}
this.uncleList = uncleList;
if (this.uncleList == null) {
this.uncleList = new CopyOnWriteArrayList<>();
}
this.parsed = true;
}
private synchronized void parseRLP() {
if (parsed) return;
RLPList params = RLP.decode2(rlpEncoded);
RLPList block = (RLPList) params.get(0);
// Parse Header
RLPList header = (RLPList) block.get(0);
this.header = new BlockHeader(header);
// Parse Transactions
RLPList txTransactions = (RLPList) block.get(1);
this.parseTxs(this.header.getTxTrieRoot(), txTransactions, false);
// Parse Uncles
RLPList uncleBlocks = (RLPList) block.get(2);
for (RLPElement rawUncle : uncleBlocks) {
RLPList uncleHeader = (RLPList) rawUncle;
BlockHeader blockData = new BlockHeader(uncleHeader);
this.uncleList.add(blockData);
}
this.parsed = true;
}
public BlockHeader getHeader() {
parseRLP();
return this.header;
}
public byte[] getHash() {
parseRLP();
return this.header.getHash();
}
public byte[] getParentHash() {
parseRLP();
return this.header.getParentHash();
}
public byte[] getUnclesHash() {
parseRLP();
return this.header.getUnclesHash();
}
public byte[] getCoinbase() {
parseRLP();
return this.header.getCoinbase();
}
public byte[] getStateRoot() {
parseRLP();
return this.header.getStateRoot();
}
public void setStateRoot(byte[] stateRoot) {
parseRLP();
this.header.setStateRoot(stateRoot);
}
public byte[] getTxTrieRoot() {
parseRLP();
return this.header.getTxTrieRoot();
}
public byte[] getReceiptsRoot() {
parseRLP();
return this.header.getReceiptsRoot();
}
public byte[] getLogBloom() {
parseRLP();
return this.header.getLogsBloom();
}
public byte[] getDifficulty() {
parseRLP();
return this.header.getDifficulty();
}
public BigInteger getDifficultyBI() {
parseRLP();
return this.header.getDifficultyBI();
}
public BigInteger getCumulativeDifficulty() {
parseRLP();
BigInteger calcDifficulty = new BigInteger(1, this.header.getDifficulty());
for (BlockHeader uncle : uncleList) {
calcDifficulty = calcDifficulty.add(new BigInteger(1, uncle.getDifficulty()));
}
return calcDifficulty;
}
public long getTimestamp() {
parseRLP();
return this.header.getTimestamp();
}
public long getNumber() {
parseRLP();
return this.header.getNumber();
}
public byte[] getGasLimit() {
parseRLP();
return this.header.getGasLimit();
}
public long getGasUsed() {
parseRLP();
return this.header.getGasUsed();
}
public byte[] getExtraData() {
parseRLP();
return this.header.getExtraData();
}
public byte[] getMixHash() {
parseRLP();
return this.header.getMixHash();
}
public byte[] getNonce() {
parseRLP();
return this.header.getNonce();
}
public void setNonce(byte[] nonce) {
this.header.setNonce(nonce);
rlpEncoded = null;
}
public void setMixHash(byte[] hash) {
this.header.setMixHash(hash);
rlpEncoded = null;
}
public void setExtraData(byte[] data) {
this.header.setExtraData(data);
rlpEncoded = null;
}
public List<Transaction> getTransactionsList() {
parseRLP();
return transactionsList;
}
public List<BlockHeader> getUncleList() {
parseRLP();
return uncleList;
}
private StringBuffer toStringBuff = new StringBuffer();
// [parent_hash, uncles_hash, coinbase, state_root, tx_trie_root,
// difficulty, number, minGasPrice, gasLimit, gasUsed, timestamp,
// extradata, nonce]
@Override
public String toString() {
parseRLP();
toStringBuff.setLength(0);
toStringBuff.append(toHexString(this.getEncoded())).append("\n");
toStringBuff.append("BlockData [ ");
toStringBuff.append(header.toString());
if (!getUncleList().isEmpty()) {
toStringBuff.append("Uncles [\n");
for (BlockHeader uncle : getUncleList()) {
toStringBuff.append(uncle.toString());
toStringBuff.append("\n");
}
toStringBuff.append("]\n");
} else {
toStringBuff.append("Uncles []\n");
}
if (!getTransactionsList().isEmpty()) {
toStringBuff.append("Txs [\n");
for (Transaction tx : getTransactionsList()) {
toStringBuff.append(tx);
toStringBuff.append("\n");
}
toStringBuff.append("]\n");
} else {
toStringBuff.append("Txs []\n");
}
toStringBuff.append("]");
return toStringBuff.toString();
}
public String toFlatString() {
parseRLP();
toStringBuff.setLength(0);
toStringBuff.append("BlockData [");
toStringBuff.append(header.toFlatString());
for (Transaction tx : getTransactionsList()) {
toStringBuff.append("\n");
toStringBuff.append(tx.toString());
}
toStringBuff.append("]");
return toStringBuff.toString();
}
private byte[] parseTxs(RLPList txTransactions, boolean validate) {
Trie<byte[]> txsState = new TrieImpl();
for (int i = 0; i < txTransactions.size(); i++) {
RLPElement transactionRaw = txTransactions.get(i);
Transaction tx = new Transaction(transactionRaw.getRLPData());
if (validate) tx.verify();
this.transactionsList.add(tx);
txsState.put(RLP.encodeInt(i), transactionRaw.getRLPData());
}
return txsState.getRootHash();
}
private boolean parseTxs(byte[] expectedRoot, RLPList txTransactions, boolean validate) {
byte[] rootHash = parseTxs(txTransactions, validate);
String calculatedRoot = Hex.toHexString(rootHash);
if (!calculatedRoot.equals(Hex.toHexString(expectedRoot))) {
logger.debug("Transactions trie root validation failed for block #{}", this.header.getNumber());
return false;
}
return true;
}
/**
* check if param block is son of this block
*
* @param block - possible a son of this
* @return - true if this block is parent of param block
*/
public boolean isParentOf(Block block) {
return Arrays.areEqual(this.getHash(), block.getParentHash());
}
public boolean isGenesis() {
return this.header.isGenesis();
}
public boolean isEqual(Block block) {
return Arrays.areEqual(this.getHash(), block.getHash());
}
private byte[] getTransactionsEncoded() {
byte[][] transactionsEncoded = new byte[transactionsList.size()][];
int i = 0;
for (Transaction tx : transactionsList) {
transactionsEncoded[i] = tx.getEncoded();
++i;
}
return RLP.encodeList(transactionsEncoded);
}
private byte[] getUnclesEncoded() {
byte[][] unclesEncoded = new byte[uncleList.size()][];
int i = 0;
for (BlockHeader uncle : uncleList) {
unclesEncoded[i] = uncle.getEncoded();
++i;
}
return RLP.encodeList(unclesEncoded);
}
public void addUncle(BlockHeader uncle) {
uncleList.add(uncle);
this.getHeader().setUnclesHash(sha3(getUnclesEncoded()));
rlpEncoded = null;
}
public byte[] getEncoded() {
if (rlpEncoded == null) {
byte[] header = this.header.getEncoded();
List<byte[]> block = getBodyElements();
block.add(0, header);
byte[][] elements = block.toArray(new byte[block.size()][]);
this.rlpEncoded = RLP.encodeList(elements);
}
return rlpEncoded;
}
public byte[] getEncodedWithoutNonce() {
parseRLP();
return this.header.getEncodedWithoutNonce();
}
public byte[] getEncodedBody() {
List<byte[]> body = getBodyElements();
byte[][] elements = body.toArray(new byte[body.size()][]);
return RLP.encodeList(elements);
}
private List<byte[]> getBodyElements() {
parseRLP();
byte[] transactions = getTransactionsEncoded();
byte[] uncles = getUnclesEncoded();
List<byte[]> body = new ArrayList<>();
body.add(transactions);
body.add(uncles);
return body;
}
public String getShortHash() {
parseRLP();
return Hex.toHexString(getHash()).substring(0, 6);
}
public String getShortDescr() {
return "#" + getNumber() + " (" + Hex.toHexString(getHash()).substring(0,6) + " <~ "
+ Hex.toHexString(getParentHash()).substring(0,6) + ") Txs:" + getTransactionsList().size() +
", Unc: " + getUncleList().size();
}
public static class Builder {
private BlockHeader header;
private byte[] body;
public Builder withHeader(BlockHeader header) {
this.header = header;
return this;
}
public Builder withBody(byte[] body) {
this.body = body;
return this;
}
public Block create() {
if (header == null || body == null) {
return null;
}
Block block = new Block();
block.header = header;
block.parsed = true;
RLPList items = (RLPList) RLP.decode2(body).get(0);
RLPList transactions = (RLPList) items.get(0);
RLPList uncles = (RLPList) items.get(1);
if (!block.parseTxs(header.getTxTrieRoot(), transactions, false)) {
return null;
}
byte[] unclesHash = HashUtil.sha3(uncles.getRLPData());
if (!java.util.Arrays.equals(header.getUnclesHash(), unclesHash)) {
return null;
}
for (RLPElement rawUncle : uncles) {
RLPList uncleHeader = (RLPList) rawUncle;
BlockHeader blockData = new BlockHeader(uncleHeader);
block.uncleList.add(blockData);
}
return block;
}
}
public static final MemSizeEstimator<Block> MemEstimator = block -> {
if (block == null) return 0;
long txSize = block.transactionsList.stream().mapToLong(Transaction.MemEstimator::estimateSize).sum() + 16;
return BlockHeader.MAX_HEADER_SIZE +
block.uncleList.size() * BlockHeader.MAX_HEADER_SIZE + 16 +
txSize +
ByteArrayEstimator.estimateSize(block.rlpEncoded) +
1 + // parsed flag
16; // Object header + ref
};
}
| 16,133
| 29.270169
| 115
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/BlockIdentifier.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPList;
import java.math.BigInteger;
import java.util.Arrays;
import static org.ethereum.util.ByteUtil.byteArrayToLong;
import static org.ethereum.util.ByteUtil.toHexString;
/**
* Block identifier holds block hash and number <br>
* This tuple is used in some places of the core,
* like by {@link org.ethereum.net.eth.message.EthMessageCodes#NEW_BLOCK_HASHES} message wrapper
*
* @author Mikhail Kalinin
* @since 04.09.2015
*/
public class BlockIdentifier {
/**
* Block hash
*/
private byte[] hash;
/**
* Block number
*/
private long number;
public BlockIdentifier(RLPList rlp) {
this.hash = rlp.get(0).getRLPData();
this.number = byteArrayToLong(rlp.get(1).getRLPData());
}
public BlockIdentifier(byte[] hash, long number) {
this.hash = hash;
this.number = number;
}
public byte[] getHash() {
return hash;
}
public long getNumber() {
return number;
}
public byte[] getEncoded() {
byte[] hash = RLP.encodeElement(this.hash);
byte[] number = RLP.encodeBigInteger(BigInteger.valueOf(this.number));
return RLP.encodeList(hash, number);
}
@Override
public String toString() {
return "BlockIdentifier {" +
"hash=" + toHexString(hash) +
", number=" + number +
'}';
}
}
| 2,272
| 26.385542
| 96
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/TransactionExecutionSummary.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPElement;
import org.ethereum.util.RLPList;
import org.ethereum.vm.DataWord;
import org.ethereum.vm.LogInfo;
import org.ethereum.vm.program.InternalTransaction;
import org.springframework.util.Assert;
import java.math.BigInteger;
import java.util.*;
import static java.util.Collections.*;
import static org.apache.commons.lang3.ArrayUtils.isNotEmpty;
import static org.ethereum.util.BIUtil.toBI;
public class TransactionExecutionSummary {
private Transaction tx;
private BigInteger value = BigInteger.ZERO;
private BigInteger gasPrice = BigInteger.ZERO;
private BigInteger gasLimit = BigInteger.ZERO;
private BigInteger gasUsed = BigInteger.ZERO;
private BigInteger gasLeftover = BigInteger.ZERO;
private BigInteger gasRefund = BigInteger.ZERO;
private List<DataWord> deletedAccounts = emptyList();
private List<InternalTransaction> internalTransactions = emptyList();
private Map<DataWord, DataWord> storageDiff = emptyMap();
private TransactionTouchedStorage touchedStorage = new TransactionTouchedStorage();
private byte[] result;
private List<LogInfo> logs;
private boolean failed;
private byte[] rlpEncoded;
private boolean parsed;
public TransactionExecutionSummary(Transaction transaction) {
this.tx = transaction;
this.gasLimit = toBI(transaction.getGasLimit());
this.gasPrice = toBI(transaction.getGasPrice());
this.value = toBI(transaction.getValue());
}
public TransactionExecutionSummary(byte[] rlpEncoded) {
this.rlpEncoded = rlpEncoded;
this.parsed = false;
}
public void rlpParse() {
if (parsed) return;
RLPList decodedTxList = RLP.decode2(rlpEncoded);
RLPList summary = (RLPList) decodedTxList.get(0);
this.tx = new Transaction(summary.get(0).getRLPData());
this.value = decodeBigInteger(summary.get(1).getRLPData());
this.gasPrice = decodeBigInteger(summary.get(2).getRLPData());
this.gasLimit = decodeBigInteger(summary.get(3).getRLPData());
this.gasUsed = decodeBigInteger(summary.get(4).getRLPData());
this.gasLeftover = decodeBigInteger(summary.get(5).getRLPData());
this.gasRefund = decodeBigInteger(summary.get(6).getRLPData());
this.deletedAccounts = decodeDeletedAccounts((RLPList) summary.get(7));
this.internalTransactions = decodeInternalTransactions((RLPList) summary.get(8));
this.touchedStorage = decodeTouchedStorage(summary.get(9));
this.result = summary.get(10).getRLPData();
this.logs = decodeLogs((RLPList) summary.get(11));
byte[] failed = summary.get(12).getRLPData();
this.failed = isNotEmpty(failed) && RLP.decodeInt(failed, 0) == 1;
}
private static BigInteger decodeBigInteger(byte[] encoded) {
return ByteUtil.bytesToBigInteger(encoded);
}
public byte[] getEncoded() {
if (rlpEncoded != null) return rlpEncoded;
this.rlpEncoded = RLP.encodeList(
this.tx.getEncoded(),
RLP.encodeBigInteger(this.value),
RLP.encodeBigInteger(this.gasPrice),
RLP.encodeBigInteger(this.gasLimit),
RLP.encodeBigInteger(this.gasUsed),
RLP.encodeBigInteger(this.gasLeftover),
RLP.encodeBigInteger(this.gasRefund),
encodeDeletedAccounts(this.deletedAccounts),
encodeInternalTransactions(this.internalTransactions),
encodeTouchedStorage(this.touchedStorage),
RLP.encodeElement(this.result),
encodeLogs(this.logs),
RLP.encodeInt(this.failed ? 1 : 0)
);
return rlpEncoded;
}
public static byte[] encodeTouchedStorage(TransactionTouchedStorage touchedStorage) {
Collection<TransactionTouchedStorage.Entry> entries = touchedStorage.getEntries();
byte[][] result = new byte[entries.size()][];
int i = 0;
for (TransactionTouchedStorage.Entry entry : entries) {
byte[] key = RLP.encodeElement(entry.getKey().getData());
byte[] value = RLP.encodeElement(entry.getValue().getData());
byte[] changed = RLP.encodeInt(entry.isChanged() ? 1 : 0);
result[i++] = RLP.encodeList(key, value, changed);
}
return RLP.encodeList(result);
}
public static TransactionTouchedStorage decodeTouchedStorage(RLPElement encoded) {
TransactionTouchedStorage result = new TransactionTouchedStorage();
for (RLPElement entry : (RLPList) encoded) {
RLPList asList = (RLPList) entry;
DataWord key = DataWord.of(asList.get(0).getRLPData());
DataWord value = DataWord.of(asList.get(1).getRLPData());
byte[] changedBytes = asList.get(2).getRLPData();
boolean changed = isNotEmpty(changedBytes) && RLP.decodeInt(changedBytes, 0) == 1;
result.add(new TransactionTouchedStorage.Entry(key, value, changed));
}
return result;
}
private static List<LogInfo> decodeLogs(RLPList logs) {
ArrayList<LogInfo> result = new ArrayList<>();
for (RLPElement log : logs) {
result.add(new LogInfo(log.getRLPData()));
}
return result;
}
private static byte[] encodeLogs(List<LogInfo> logs) {
byte[][] result = new byte[logs.size()][];
for (int i = 0; i < logs.size(); i++) {
LogInfo log = logs.get(i);
result[i] = log.getEncoded();
}
return RLP.encodeList(result);
}
private static byte[] encodeStorageDiff(Map<DataWord, DataWord> storageDiff) {
byte[][] result = new byte[storageDiff.size()][];
int i = 0;
for (Map.Entry<DataWord, DataWord> entry : storageDiff.entrySet()) {
byte[] key = RLP.encodeElement(entry.getKey().getData());
byte[] value = RLP.encodeElement(entry.getValue().getData());
result[i++] = RLP.encodeList(key, value);
}
return RLP.encodeList(result);
}
private static Map<DataWord, DataWord> decodeStorageDiff(RLPList storageDiff) {
Map<DataWord, DataWord> result = new HashMap<>();
for (RLPElement entry : storageDiff) {
DataWord key = DataWord.of(((RLPList) entry).get(0).getRLPData());
DataWord value = DataWord.of(((RLPList) entry).get(1).getRLPData());
result.put(key, value);
}
return result;
}
private static byte[] encodeInternalTransactions(List<InternalTransaction> internalTransactions) {
byte[][] result = new byte[internalTransactions.size()][];
for (int i = 0; i < internalTransactions.size(); i++) {
InternalTransaction transaction = internalTransactions.get(i);
result[i] = transaction.getEncoded();
}
return RLP.encodeList(result);
}
private static List<InternalTransaction> decodeInternalTransactions(RLPList internalTransactions) {
List<InternalTransaction> result = new ArrayList<>();
for (RLPElement internalTransaction : internalTransactions) {
result.add(new InternalTransaction(internalTransaction.getRLPData()));
}
return result;
}
private static byte[] encodeDeletedAccounts(List<DataWord> deletedAccounts) {
byte[][] result = new byte[deletedAccounts.size()][];
for (int i = 0; i < deletedAccounts.size(); i++) {
DataWord deletedAccount = deletedAccounts.get(i);
result[i] = RLP.encodeElement(deletedAccount.getData());
}
return RLP.encodeList(result);
}
private static List<DataWord> decodeDeletedAccounts(RLPList deletedAccounts) {
List<DataWord> result = new ArrayList<>();
for (RLPElement deletedAccount : deletedAccounts) {
result.add(DataWord.of(deletedAccount.getRLPData()));
}
return result;
}
public Transaction getTransaction() {
if (!parsed) rlpParse();
return tx;
}
public byte[] getTransactionHash() {
return getTransaction().getHash();
}
private BigInteger calcCost(BigInteger gas) {
return gasPrice.multiply(gas);
}
public BigInteger getFee() {
if (!parsed) rlpParse();
return calcCost(gasLimit.subtract(gasLeftover.add(gasRefund)));
}
public BigInteger getRefund() {
if (!parsed) rlpParse();
return calcCost(gasRefund);
}
public BigInteger getLeftover() {
if (!parsed) rlpParse();
return calcCost(gasLeftover);
}
public BigInteger getGasPrice() {
if (!parsed) rlpParse();
return gasPrice;
}
public BigInteger getGasLimit() {
if (!parsed) rlpParse();
return gasLimit;
}
public BigInteger getGasUsed() {
if (!parsed) rlpParse();
return gasUsed;
}
public BigInteger getGasLeftover() {
if (!parsed) rlpParse();
return gasLeftover;
}
public BigInteger getValue() {
if (!parsed) rlpParse();
return value;
}
public List<DataWord> getDeletedAccounts() {
if (!parsed) rlpParse();
return deletedAccounts;
}
public List<InternalTransaction> getInternalTransactions() {
if (!parsed) rlpParse();
return internalTransactions;
}
@Deprecated
/* Use getTouchedStorage().getAll() instead */
public Map<DataWord, DataWord> getStorageDiff() {
if (!parsed) rlpParse();
return storageDiff;
}
public BigInteger getGasRefund() {
if (!parsed) rlpParse();
return gasRefund;
}
public boolean isFailed() {
if (!parsed) rlpParse();
return failed;
}
public byte[] getResult() {
if (!parsed) rlpParse();
return result;
}
public List<LogInfo> getLogs() {
if (!parsed) rlpParse();
return logs;
}
public TransactionTouchedStorage getTouchedStorage() {
return touchedStorage;
}
public static Builder builderFor(Transaction transaction) {
return new Builder(transaction);
}
public static class Builder {
private final TransactionExecutionSummary summary;
Builder(Transaction transaction) {
Assert.notNull(transaction, "Cannot build TransactionExecutionSummary for null transaction.");
summary = new TransactionExecutionSummary(transaction);
}
public Builder gasUsed(BigInteger gasUsed) {
summary.gasUsed = gasUsed;
return this;
}
public Builder gasLeftover(BigInteger gasLeftover) {
summary.gasLeftover = gasLeftover;
return this;
}
public Builder gasRefund(BigInteger gasRefund) {
summary.gasRefund = gasRefund;
return this;
}
public Builder internalTransactions(List<InternalTransaction> internalTransactions) {
summary.internalTransactions = unmodifiableList(internalTransactions);
return this;
}
public Builder deletedAccounts(Set<DataWord> deletedAccounts) {
summary.deletedAccounts = new ArrayList<>();
for (DataWord account : deletedAccounts) {
summary.deletedAccounts.add(account);
}
return this;
}
public Builder storageDiff(Map<DataWord, DataWord> storageDiff) {
summary.storageDiff = unmodifiableMap(storageDiff);
return this;
}
public Builder touchedStorage(Map<DataWord, DataWord> touched, Map<DataWord, DataWord> changed) {
summary.touchedStorage.addReading(touched);
summary.touchedStorage.addWriting(changed);
return this;
}
public Builder markAsFailed() {
summary.failed = true;
return this;
}
public Builder logs(List<LogInfo> logs) {
summary.logs = logs;
return this;
}
public Builder result(byte[] result) {
summary.result = result;
return this;
}
public TransactionExecutionSummary build() {
summary.parsed = true;
if (summary.failed) {
for (InternalTransaction transaction : summary.internalTransactions) {
transaction.reject();
}
}
return summary;
}
}
}
| 13,489
| 32.557214
| 106
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/CallTransaction.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core;
import static java.lang.String.format;
import static org.apache.commons.lang3.ArrayUtils.subarray;
import static org.apache.commons.lang3.StringUtils.stripEnd;
import static org.ethereum.crypto.HashUtil.sha3;
import static org.ethereum.solidity.SolidityType.IntType;
import static org.ethereum.util.ByteUtil.longToBytesNoLeadZeroes;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.ethereum.solidity.SolidityType;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.FastByteComparisons;
import org.ethereum.vm.LogInfo;
import org.spongycastle.util.encoders.Hex;
/**
* Creates a contract function call transaction.
* Serializes arguments according to the function ABI .
*
* Created by Anton Nashatyrev on 25.08.2015.
*/
public class CallTransaction {
private final static ObjectMapper DEFAULT_MAPPER = new ObjectMapper()
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL);
public static Transaction createRawTransaction(long nonce, long gasPrice, long gasLimit, String toAddress,
long value, byte[] data) {
Transaction tx = new Transaction(longToBytesNoLeadZeroes(nonce),
longToBytesNoLeadZeroes(gasPrice),
longToBytesNoLeadZeroes(gasLimit),
toAddress == null ? null : Hex.decode(toAddress),
longToBytesNoLeadZeroes(value),
data,
null);
return tx;
}
public static Transaction createCallTransaction(long nonce, long gasPrice, long gasLimit, String toAddress,
long value, Function callFunc, Object ... funcArgs) {
byte[] callData = callFunc.encode(funcArgs);
return createRawTransaction(nonce, gasPrice, gasLimit, toAddress, value, callData);
}
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class Param {
public Boolean indexed;
public String name;
public SolidityType type;
@JsonGetter("type")
public String getType() {
return type.getName();
}
}
public enum StateMutabilityType {
pure,
view,
nonpayable,
payable
}
public enum FunctionType {
constructor,
function,
event,
fallback
}
public static class Function {
public boolean anonymous;
public boolean constant;
public boolean payable;
public String name = "";
public Param[] inputs = new Param[0];
public Param[] outputs = new Param[0];
public FunctionType type;
public StateMutabilityType stateMutability;
private Function() {}
public byte[] encode(Object ... args) {
return ByteUtil.merge(encodeSignature(), encodeArguments(args));
}
public byte[] encodeArguments(Object ... args) {
if (args.length > inputs.length) throw new RuntimeException("Too many arguments: " + args.length + " > " + inputs.length);
int staticSize = 0;
int dynamicCnt = 0;
// calculating static size and number of dynamic params
for (int i = 0; i < args.length; i++) {
Param param = inputs[i];
if (param.type.isDynamicType()) {
dynamicCnt++;
}
staticSize += param.type.getFixedSize();
}
byte[][] bb = new byte[args.length + dynamicCnt][];
int curDynamicPtr = staticSize;
int curDynamicCnt = 0;
for (int i = 0; i < args.length; i++) {
if (inputs[i].type.isDynamicType()) {
byte[] dynBB = inputs[i].type.encode(args[i]);
bb[i] = SolidityType.IntType.encodeInt(curDynamicPtr);
bb[args.length + curDynamicCnt] = dynBB;
curDynamicCnt++;
curDynamicPtr += dynBB.length;
} else {
bb[i] = inputs[i].type.encode(args[i]);
}
}
return ByteUtil.merge(bb);
}
private Object[] decode(byte[] encoded, Param[] params) {
Object[] ret = new Object[params.length];
int off = 0;
for (int i = 0; i < params.length; i++) {
if (params[i].type.isDynamicType()) {
ret[i] = params[i].type.decode(encoded, IntType.decodeInt(encoded, off).intValue());
} else {
ret[i] = params[i].type.decode(encoded, off);
}
off += params[i].type.getFixedSize();
}
return ret;
}
public Object[] decode(byte[] encoded) {
return decode(subarray(encoded, 4, encoded.length), inputs);
}
public Object[] decodeResult(byte[] encodedRet) {
return decode(encodedRet, outputs);
}
public String formatSignature() {
StringBuilder paramsTypes = new StringBuilder();
for (Param param : inputs) {
paramsTypes.append(param.type.getCanonicalName()).append(",");
}
return format("%s(%s)", name, stripEnd(paramsTypes.toString(), ","));
}
public byte[] encodeSignatureLong() {
String signature = formatSignature();
byte[] sha3Fingerprint = sha3(signature.getBytes());
return sha3Fingerprint;
}
public byte[] encodeSignature() {
return Arrays.copyOfRange(encodeSignatureLong(), 0, 4);
}
@Override
public String toString() {
return formatSignature();
}
public static Function fromJsonInterface(String json) {
try {
return DEFAULT_MAPPER.readValue(json, Function.class);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static Function fromSignature(String funcName, String ... paramTypes) {
return fromSignature(funcName, paramTypes, new String[0]);
}
public static Function fromSignature(String funcName, String[] paramTypes, String[] resultTypes) {
Function ret = new Function();
ret.name = funcName;
ret.constant = false;
ret.type = FunctionType.function;
ret.inputs = new Param[paramTypes.length];
for (int i = 0; i < paramTypes.length; i++) {
ret.inputs[i] = new Param();
ret.inputs[i].name = "param" + i;
ret.inputs[i].type = SolidityType.getType(paramTypes[i]);
}
ret.outputs = new Param[resultTypes.length];
for (int i = 0; i < resultTypes.length; i++) {
ret.outputs[i] = new Param();
ret.outputs[i].name = "res" + i;
ret.outputs[i].type = SolidityType.getType(resultTypes[i]);
}
return ret;
}
}
public static class Contract {
public Contract(String jsonInterface) {
try {
functions = new ObjectMapper().readValue(jsonInterface, Function[].class);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public Function getByName(String name) {
for (Function function : functions) {
if (name.equals(function.name)) {
return function;
}
}
return null;
}
public Function getConstructor() {
for (Function function : functions) {
if (function.type == FunctionType.constructor) {
return function;
}
}
return null;
}
private Function getBySignatureHash(byte[] hash) {
if (hash.length == 4 ) {
for (Function function : functions) {
if (FastByteComparisons.equal(function.encodeSignature(), hash)) {
return function;
}
}
} else if (hash.length == 32 ) {
for (Function function : functions) {
if (FastByteComparisons.equal(function.encodeSignatureLong(), hash)) {
return function;
}
}
} else {
throw new RuntimeException("Function signature hash should be 4 or 32 bytes length");
}
return null;
}
/**
* Parses function and its arguments from transaction invocation binary data
*/
public Invocation parseInvocation(byte[] data) {
if (data.length < 4) throw new RuntimeException("Invalid data length: " + data.length);
Function function = getBySignatureHash(Arrays.copyOfRange(data, 0, 4));
if (function == null) throw new RuntimeException("Can't find function/event by it signature");
Object[] args = function.decode(data);
return new Invocation(this, function, args);
}
/**
* Parses Solidity Event and its data members from transaction receipt LogInfo
* Finds corresponding event by its signature hash and thus is not applicable to
* anonymous events
*/
public Invocation parseEvent(LogInfo eventLog) {
CallTransaction.Function event = getBySignatureHash(eventLog.getTopics().get(0).getData());
int indexedArg = 1;
if (event == null) return null;
List<Object> indexedArgs = new ArrayList<>();
List<Param> unindexed = new ArrayList<>();
for (Param input : event.inputs) {
if (input.indexed) {
byte[] topicBytes = eventLog.getTopics().get(indexedArg++).getData();
Object decodedTopic;
if (input.type.isDynamicType()) {
// If arrays (including string and bytes) are used as indexed arguments,
// the Keccak-256 hash of it is stored as topic instead.
decodedTopic = SolidityType.Bytes32Type.decodeBytes32(topicBytes, 0);
} else {
decodedTopic = input.type.decode(topicBytes);
}
indexedArgs.add(decodedTopic);
} else {
unindexed.add(input);
}
}
Object[] unindexedArgs = event.decode(eventLog.getData(), unindexed.toArray(new Param[unindexed.size()]));
Object[] args = new Object[event.inputs.length];
int unindexedIndex = 0;
int indexedIndex = 0;
for (int i = 0; i < args.length; i++) {
if (event.inputs[i].indexed) {
args[i] = indexedArgs.get(indexedIndex++);
continue;
}
args[i] = unindexedArgs[unindexedIndex++];
}
return new Invocation(this, event, args);
}
public Function[] functions;
}
/**
* Represents either function invocation with its arguments
* or Event instance with its data members
*/
public static class Invocation {
public final Contract contract;
public final Function function;
public final Object[] args;
public Invocation(Contract contract, Function function, Object[] args) {
this.contract = contract;
this.function = function;
this.args = args;
}
@Override
public String toString() {
return "[" + "contract=" + contract +
(function.type == FunctionType.event ? ", event=" : ", function=")
+ function + ", args=" + Arrays.toString(args) + ']';
}
}
}
| 13,180
| 35.921569
| 134
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/Repository.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core;
import org.ethereum.db.ByteArrayWrapper;
import org.ethereum.db.ContractDetails;
import org.ethereum.vm.DataWord;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Set;
/**
* @author Roman Mandeleil
* @since 08.09.2014
*/
public interface Repository extends org.ethereum.facade.Repository{
/**
* Create a new account in the database
*
* @param addr of the contract
* @return newly created account state
*/
AccountState createAccount(byte[] addr);
/**
* @param addr - account to check
* @return - true if account exist,
* false otherwise
*/
boolean isExist(byte[] addr);
/**
* Retrieve an account
*
* @param addr of the account
* @return account state as stored in the database
*/
AccountState getAccountState(byte[] addr);
/**
* Deletes the account
*
* @param addr of the account
*/
void delete(byte[] addr);
/**
* Increase the account nonce of the given account by one
*
* @param addr of the account
* @return new value of the nonce
*/
BigInteger increaseNonce(byte[] addr);
/**
* Sets the account nonce of the given account
*
* @param addr of the account
* @param nonce new nonce
* @return new value of the nonce
*/
BigInteger setNonce(byte[] addr, BigInteger nonce);
/**
* Get current nonce of a given account
*
* @param addr of the account
* @return value of the nonce
*/
BigInteger getNonce(byte[] addr);
/**
* Retrieve contract details for a given account from the database
*
* @param addr of the account
* @return new contract details
*/
ContractDetails getContractDetails(byte[] addr);
boolean hasContractDetails(byte[] addr);
/**
* Store code associated with an account
*
* @param addr for the account
* @param code that will be associated with this account
*/
void saveCode(byte[] addr, byte[] code);
/**
* Retrieve the code associated with an account
*
* @param addr of the account
* @return code in byte-array format
*/
byte[] getCode(byte[] addr);
/**
* Retrieve the code hash associated with an account
*
* @param addr of the account
* @return code hash
*/
byte[] getCodeHash(byte[] addr);
/**
* Put a value in storage of an account at a given key
*
* @param addr of the account
* @param key of the data to store
* @param value is the data to store
*/
void addStorageRow(byte[] addr, DataWord key, DataWord value);
/**
* Retrieve storage value from an account for a given key
*
* @param addr of the account
* @param key associated with this value
* @return data in the form of a <code>DataWord</code>
*/
DataWord getStorageValue(byte[] addr, DataWord key);
/**
* Retrieve balance of an account
*
* @param addr of the account
* @return balance of the account as a <code>BigInteger</code> value
*/
BigInteger getBalance(byte[] addr);
/**
* Add value to the balance of an account
*
* @param addr of the account
* @param value to be added
* @return new balance of the account
*/
BigInteger addBalance(byte[] addr, BigInteger value);
/**
* @return Returns set of all the account addresses
*/
Set<byte[]> getAccountsKeys();
/**
* Dump the full state of the current repository into a file with JSON format
* It contains all the contracts/account, their attributes and
*
* @param block of the current state
* @param gasUsed the amount of gas used in the block until that point
* @param txNumber is the number of the transaction for which the dump has to be made
* @param txHash is the hash of the given transaction.
* If null, the block state post coinbase reward is dumped.
*/
void dumpState(Block block, long gasUsed, int txNumber, byte[] txHash);
/**
* Save a snapshot and start tracking future changes
*
* @return the tracker repository
*/
Repository startTracking();
void flush();
void flushNoReconnect();
/**
* Store all the temporary changes made
* to the repository in the actual database
*/
void commit();
/**
* Undo all the changes made so far
* to a snapshot of the repository
*/
void rollback();
/**
* Return to one of the previous snapshots
* by moving the root.
*
* @param root - new root
*/
void syncToRoot(byte[] root);
/**
* Check to see if the current repository has an open connection to the database
*
* @return <tt>true</tt> if connection to database is open
*/
boolean isClosed();
/**
* Close the database
*/
void close();
/**
* Reset
*/
void reset();
void updateBatch(HashMap<ByteArrayWrapper, AccountState> accountStates,
HashMap<ByteArrayWrapper, ContractDetails> contractDetailes);
byte[] getRoot();
void loadAccount(byte[] addr, HashMap<ByteArrayWrapper, AccountState> cacheAccounts,
HashMap<ByteArrayWrapper, ContractDetails> cacheDetails);
Repository getSnapshotTo(byte[] root);
/**
* Clones repository so changes made to this repository are
* not reflected in its clone.
*/
Repository clone();
}
| 6,373
| 25.016327
| 89
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/TransactionInfo.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core;
import org.ethereum.core.Bloom;
import org.ethereum.core.Transaction;
import org.ethereum.core.TransactionReceipt;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPElement;
import org.ethereum.util.RLPItem;
import org.ethereum.util.RLPList;
import org.ethereum.vm.LogInfo;
import java.math.BigInteger;
/**
* Contains Transaction execution info:
* its receipt and execution context
* If the transaction is still in pending state the context is the
* hash of the parent block on top of which the transaction was executed
* If the transaction is already mined into a block the context
* is the containing block and the index of the transaction in that block
*
* Created by Ruben on 8/1/2016.
*/
public class TransactionInfo {
TransactionReceipt receipt;
byte[] blockHash;
// user for pending transaction
byte[] parentBlockHash;
int index;
public TransactionInfo(TransactionReceipt receipt, byte[] blockHash, int index) {
this.receipt = receipt;
this.blockHash = blockHash;
this.index = index;
}
/**
* Creates a pending tx info
*/
public TransactionInfo(TransactionReceipt receipt) {
this.receipt = receipt;
}
public TransactionInfo(byte[] rlp) {
RLPList params = RLP.decode2(rlp);
RLPList txInfo = (RLPList) params.get(0);
RLPList receiptRLP = (RLPList) txInfo.get(0);
RLPItem blockHashRLP = (RLPItem) txInfo.get(1);
RLPItem indexRLP = (RLPItem) txInfo.get(2);
receipt = new TransactionReceipt(receiptRLP.getRLPData());
blockHash = blockHashRLP.getRLPData();
if (indexRLP.getRLPData() == null)
index = 0;
else
index = new BigInteger(1, indexRLP.getRLPData()).intValue();
}
public void setTransaction(Transaction tx){
receipt.setTransaction(tx);
}
/* [receipt, blockHash, index] */
public byte[] getEncoded() {
byte[] receiptRLP = this.receipt.getEncoded();
byte[] blockHashRLP = RLP.encodeElement(blockHash);
byte[] indexRLP = RLP.encodeInt(index);
byte[] rlpEncoded = RLP.encodeList(receiptRLP, blockHashRLP, indexRLP);
return rlpEncoded;
}
public TransactionReceipt getReceipt(){
return receipt;
}
public byte[] getBlockHash() { return blockHash; }
public byte[] getParentBlockHash() {
return parentBlockHash;
}
public void setParentBlockHash(byte[] parentBlockHash) {
this.parentBlockHash = parentBlockHash;
}
public int getIndex() { return index; }
public boolean isPending() {
return blockHash == null;
}
}
| 3,490
| 29.893805
| 85
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/BlockSummary.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPElement;
import org.ethereum.util.RLPList;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import static org.ethereum.util.ByteUtil.toHexString;
public class BlockSummary {
private final Block block;
private final Map<byte[], BigInteger> rewards;
private final List<TransactionReceipt> receipts;
private final List<TransactionExecutionSummary> summaries;
private BigInteger totalDifficulty = BigInteger.ZERO;
public BlockSummary(byte[] rlp) {
RLPList rlpList = RLP.unwrapList(rlp);
this.block = new Block(rlpList.get(0).getRLPData());
this.rewards = decodeRewards(RLP.unwrapList(rlpList.get(1).getRLPData()));
this.summaries = decodeSummaries(RLP.unwrapList(rlpList.get(2).getRLPData()));
this.receipts = new ArrayList<>();
Map<String, TransactionReceipt> receiptByTxHash = decodeReceipts(RLP.unwrapList(rlpList.get(3).getRLPData()));
for (Transaction tx : this.block.getTransactionsList()) {
TransactionReceipt receipt = receiptByTxHash.get(toHexString(tx.getHash()));
receipt.setTransaction(tx);
this.receipts.add(receipt);
}
}
public BlockSummary(Block block, Map<byte[], BigInteger> rewards, List<TransactionReceipt> receipts, List<TransactionExecutionSummary> summaries) {
this.block = block;
this.rewards = rewards;
this.receipts = receipts;
this.summaries = summaries;
}
public Block getBlock() {
return block;
}
public List<TransactionReceipt> getReceipts() {
return receipts;
}
public List<TransactionExecutionSummary> getSummaries() {
return summaries;
}
/**
* All the mining rewards paid out for this block, including the main block rewards, uncle rewards, and transaction fees.
*/
public Map<byte[], BigInteger> getRewards() {
return rewards;
}
public void setTotalDifficulty(BigInteger totalDifficulty) {
this.totalDifficulty = totalDifficulty;
}
public BigInteger getTotalDifficulty() {
return totalDifficulty;
}
public byte[] getEncoded() {
return RLP.encodeList(
block.getEncoded(),
encodeRewards(rewards),
encodeSummaries(summaries),
encodeReceipts(receipts)
);
}
/**
* Whether this block could be new best block
* for the chain with provided old total difficulty
* @param oldTotDifficulty Total difficulty for the suggested chain
* @return True - best, False - not best
*/
public boolean betterThan(BigInteger oldTotDifficulty) {
return getTotalDifficulty().compareTo(oldTotDifficulty) > 0;
}
private static <T> byte[] encodeList(List<T> entries, Function<T, byte[]> encoder) {
byte[][] result = new byte[entries.size()][];
for (int i = 0; i < entries.size(); i++) {
result[i] = encoder.apply(entries.get(i));
}
return RLP.encodeList(result);
}
private static <T> List<T> decodeList(RLPList list, Function<byte[], T> decoder) {
List<T> result = new ArrayList<>();
for (RLPElement item : list) {
result.add(decoder.apply(item.getRLPData()));
}
return result;
}
private static <K, V> byte[] encodeMap(Map<K, V> map, Function<K, byte[]> keyEncoder, Function<V, byte[]> valueEncoder) {
byte[][] result = new byte[map.size()][];
int i = 0;
for (Map.Entry<K, V> entry : map.entrySet()) {
byte[] key = keyEncoder.apply(entry.getKey());
byte[] value = valueEncoder.apply(entry.getValue());
result[i++] = RLP.encodeList(key, value);
}
return RLP.encodeList(result);
}
private static <K, V> Map<K, V> decodeMap(RLPList list, Function<byte[], K> keyDecoder, Function<byte[], V> valueDecoder) {
Map<K, V> result = new HashMap<>();
for (RLPElement entry : list) {
K key = keyDecoder.apply(((RLPList) entry).get(0).getRLPData());
V value = valueDecoder.apply(((RLPList) entry).get(1).getRLPData());
result.put(key, value);
}
return result;
}
private static byte[] encodeSummaries(final List<TransactionExecutionSummary> summaries) {
return encodeList(summaries, TransactionExecutionSummary::getEncoded);
}
private static List<TransactionExecutionSummary> decodeSummaries(RLPList summaries) {
return decodeList(summaries, TransactionExecutionSummary::new);
}
private static byte[] encodeReceipts(List<TransactionReceipt> receipts) {
Map<String, TransactionReceipt> receiptByTxHash = new HashMap<>();
for (TransactionReceipt receipt : receipts) {
receiptByTxHash.put(toHexString(receipt.getTransaction().getHash()), receipt);
}
return encodeMap(receiptByTxHash, RLP::encodeString, TransactionReceipt::getEncoded);
}
private static Map<String, TransactionReceipt> decodeReceipts(RLPList receipts) {
return decodeMap(receipts, String::new, TransactionReceipt::new);
}
private static byte[] encodeRewards(Map<byte[], BigInteger> rewards) {
return encodeMap(rewards, RLP::encodeElement, RLP::encodeBigInteger);
}
private static Map<byte[], BigInteger> decodeRewards(RLPList rewards) {
return decodeMap(rewards, bytes -> bytes, bytes ->
ByteUtil.bytesToBigInteger(bytes)
);
}
}
| 6,562
| 35.259669
| 151
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/Transaction.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core;
import static org.apache.commons.lang3.ArrayUtils.isEmpty;
import static org.ethereum.datasource.MemSizeEstimator.ByteArrayEstimator;
import static org.ethereum.util.ByteUtil.EMPTY_BYTE_ARRAY;
import static org.ethereum.util.ByteUtil.ZERO_BYTE_ARRAY;
import java.math.BigInteger;
import java.security.SignatureException;
import java.util.Arrays;
import org.ethereum.config.BlockchainNetConfig;
import org.ethereum.crypto.ECKey;
import org.ethereum.crypto.ECKey.ECDSASignature;
import org.ethereum.crypto.ECKey.MissingPrivateKeyException;
import org.ethereum.crypto.HashUtil;
import org.ethereum.datasource.MemSizeEstimator;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPElement;
import org.ethereum.util.RLPItem;
import org.ethereum.util.RLPList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.BigIntegers;
import org.spongycastle.util.encoders.Hex;
/**
* A transaction (formally, T) is a single cryptographically
* signed instruction sent by an actor external to Ethereum.
* An external actor can be a person (via a mobile device or desktop computer)
* or could be from a piece of automated software running on a server.
* There are two types of transactions: those which result in message calls
* and those which result in the creation of new contracts.
*/
public class Transaction {
private static final Logger logger = LoggerFactory.getLogger(Transaction.class);
private static final BigInteger DEFAULT_GAS_PRICE = new BigInteger("10000000000000");
private static final BigInteger DEFAULT_BALANCE_GAS = new BigInteger("21000");
public static final int HASH_LENGTH = 32;
public static final int ADDRESS_LENGTH = 20;
/* SHA3 hash of the RLP encoded transaction */
private byte[] hash;
/* a counter used to make sure each transaction can only be processed once */
private byte[] nonce;
/* the amount of ether to transfer (calculated as wei) */
private byte[] value;
/* the address of the destination account
* In creation transaction the receive address is - 0 */
private byte[] receiveAddress;
/* the amount of ether to pay as a transaction fee
* to the miner for each unit of gas */
private byte[] gasPrice;
/* the amount of "gas" to allow for the computation.
* Gas is the fuel of the computational engine;
* every computational step taken and every byte added
* to the state or transaction list consumes some gas. */
private byte[] gasLimit;
/* An unlimited size byte array specifying
* input [data] of the message call or
* Initialization code for a new contract */
private byte[] data;
/**
* Since EIP-155, we could encode chainId in V
*/
private static final int CHAIN_ID_INC = 35;
private static final int LOWER_REAL_V = 27;
private Integer chainId = null;
/* the elliptic curve signature
* (including public key recovery bits) */
private ECDSASignature signature;
protected byte[] sendAddress;
/* Tx in encoded form */
protected byte[] rlpEncoded;
private byte[] rawHash;
/* Indicates if this transaction has been parsed
* from the RLP-encoded data */
protected boolean parsed = false;
public Transaction(byte[] rawData) {
this.rlpEncoded = rawData;
parsed = false;
}
public Transaction(byte[] nonce, byte[] gasPrice, byte[] gasLimit, byte[] receiveAddress, byte[] value, byte[] data,
Integer chainId) {
this.nonce = nonce;
this.gasPrice = gasPrice;
this.gasLimit = gasLimit;
this.receiveAddress = receiveAddress;
if (ByteUtil.isSingleZero(value)) {
this.value = EMPTY_BYTE_ARRAY;
} else {
this.value = value;
}
this.data = data;
this.chainId = chainId;
if (receiveAddress == null) {
this.receiveAddress = ByteUtil.EMPTY_BYTE_ARRAY;
}
parsed = true;
}
/**
* Warning: this transaction would not be protected by replay-attack protection mechanism
* Use {@link Transaction#Transaction(byte[], byte[], byte[], byte[], byte[], byte[], Integer)} constructor instead
* and specify the desired chainID
*/
public Transaction(byte[] nonce, byte[] gasPrice, byte[] gasLimit, byte[] receiveAddress, byte[] value, byte[] data) {
this(nonce, gasPrice, gasLimit, receiveAddress, value, data, null);
}
public Transaction(byte[] nonce, byte[] gasPrice, byte[] gasLimit, byte[] receiveAddress, byte[] value, byte[] data,
byte[] r, byte[] s, byte v, Integer chainId) {
this(nonce, gasPrice, gasLimit, receiveAddress, value, data, chainId);
this.signature = ECDSASignature.fromComponents(r, s, v);
}
/**
* Warning: this transaction would not be protected by replay-attack protection mechanism
* Use {@link Transaction#Transaction(byte[], byte[], byte[], byte[], byte[], byte[], byte[], byte[], byte, Integer)}
* constructor instead and specify the desired chainID
*/
public Transaction(byte[] nonce, byte[] gasPrice, byte[] gasLimit, byte[] receiveAddress, byte[] value, byte[] data,
byte[] r, byte[] s, byte v) {
this(nonce, gasPrice, gasLimit, receiveAddress, value, data, r, s, v, null);
}
private Integer extractChainIdFromRawSignature(BigInteger bv, byte[] r, byte[] s) {
if (r == null && s == null) return bv.intValue(); // EIP 86
if (bv.bitLength() > 31) return Integer.MAX_VALUE; // chainId is limited to 31 bits, longer are not valid for now
long v = bv.longValue();
if (v == LOWER_REAL_V || v == (LOWER_REAL_V + 1)) return null;
return (int) ((v - CHAIN_ID_INC) / 2);
}
private byte getRealV(BigInteger bv) {
if (bv.bitLength() > 31) return 0; // chainId is limited to 31 bits, longer are not valid for now
long v = bv.longValue();
if (v == LOWER_REAL_V || v == (LOWER_REAL_V + 1)) return (byte) v;
byte realV = LOWER_REAL_V;
int inc = 0;
if ((int) v % 2 == 0) inc = 1;
return (byte) (realV + inc);
}
public long transactionCost(BlockchainNetConfig config, Block block){
rlpParse();
return config.getConfigForBlock(block.getNumber()).
getTransactionCost(this);
}
public synchronized void verify() {
rlpParse();
validate();
}
public synchronized void rlpParse() {
if (parsed) return;
try {
RLPList decodedTxList = RLP.decode2(rlpEncoded);
RLPList transaction = (RLPList) decodedTxList.get(0);
// Basic verification
if (transaction.size() > 9 ) throw new RuntimeException("Too many RLP elements");
for (RLPElement rlpElement : transaction) {
if (!(rlpElement instanceof RLPItem))
throw new RuntimeException("Transaction RLP elements shouldn't be lists");
}
this.nonce = transaction.get(0).getRLPData();
this.gasPrice = transaction.get(1).getRLPData();
this.gasLimit = transaction.get(2).getRLPData();
this.receiveAddress = transaction.get(3).getRLPData();
this.value = transaction.get(4).getRLPData();
this.data = transaction.get(5).getRLPData();
// only parse signature in case tx is signed
if (transaction.get(6).getRLPData() != null) {
byte[] vData = transaction.get(6).getRLPData();
BigInteger v = ByteUtil.bytesToBigInteger(vData);
byte[] r = transaction.get(7).getRLPData();
byte[] s = transaction.get(8).getRLPData();
this.chainId = extractChainIdFromRawSignature(v, r, s);
if (r != null && s != null) {
this.signature = ECDSASignature.fromComponents(r, s, getRealV(v));
}
} else {
logger.debug("RLP encoded tx is not signed!");
}
this.hash = HashUtil.sha3(rlpEncoded);
this.parsed = true;
} catch (Exception e) {
throw new RuntimeException("Error on parsing RLP", e);
}
}
private void validate() {
if (getNonce().length > HASH_LENGTH) throw new RuntimeException("Nonce is not valid");
if (receiveAddress != null && receiveAddress.length != 0 && receiveAddress.length != ADDRESS_LENGTH)
throw new RuntimeException("Receive address is not valid");
if (gasLimit.length > HASH_LENGTH)
throw new RuntimeException("Gas Limit is not valid");
if (gasPrice != null && gasPrice.length > HASH_LENGTH)
throw new RuntimeException("Gas Price is not valid");
if (value != null && value.length > HASH_LENGTH)
throw new RuntimeException("Value is not valid");
if (getSignature() != null) {
if (BigIntegers.asUnsignedByteArray(signature.r).length > HASH_LENGTH)
throw new RuntimeException("Signature R is not valid");
if (BigIntegers.asUnsignedByteArray(signature.s).length > HASH_LENGTH)
throw new RuntimeException("Signature S is not valid");
if (getSender() != null && getSender().length != ADDRESS_LENGTH)
throw new RuntimeException("Sender is not valid");
}
}
public boolean isParsed() {
return parsed;
}
public byte[] getHash() {
if (!isEmpty(hash)) return hash;
rlpParse();
getEncoded();
return hash;
}
public byte[] getRawHash() {
rlpParse();
if (rawHash != null) return rawHash;
byte[] plainMsg = this.getEncodedRaw();
return rawHash = HashUtil.sha3(plainMsg);
}
public byte[] getNonce() {
rlpParse();
return nonce == null ? ZERO_BYTE_ARRAY : nonce;
}
protected void setNonce(byte[] nonce) {
this.nonce = nonce;
parsed = true;
}
public boolean isValueTx() {
rlpParse();
return value != null;
}
public byte[] getValue() {
rlpParse();
return value == null ? ZERO_BYTE_ARRAY : value;
}
protected void setValue(byte[] value) {
this.value = value;
parsed = true;
}
public byte[] getReceiveAddress() {
rlpParse();
return receiveAddress;
}
protected void setReceiveAddress(byte[] receiveAddress) {
this.receiveAddress = receiveAddress;
parsed = true;
}
public byte[] getGasPrice() {
rlpParse();
return gasPrice == null ? ZERO_BYTE_ARRAY : gasPrice;
}
protected void setGasPrice(byte[] gasPrice) {
this.gasPrice = gasPrice;
parsed = true;
}
public byte[] getGasLimit() {
rlpParse();
return gasLimit == null ? ZERO_BYTE_ARRAY : gasLimit;
}
protected void setGasLimit(byte[] gasLimit) {
this.gasLimit = gasLimit;
parsed = true;
}
public long nonZeroDataBytes() {
if (data == null) return 0;
int counter = 0;
for (final byte aData : data) {
if (aData != 0) ++counter;
}
return counter;
}
public long zeroDataBytes() {
if (data == null) return 0;
int counter = 0;
for (final byte aData : data) {
if (aData == 0) ++counter;
}
return counter;
}
public byte[] getData() {
rlpParse();
return data;
}
protected void setData(byte[] data) {
this.data = data;
parsed = true;
}
public ECDSASignature getSignature() {
rlpParse();
return signature;
}
public byte[] getContractAddress() {
if (!isContractCreation()) return null;
return HashUtil.calcNewAddr(this.getSender(), this.getNonce());
}
public boolean isContractCreation() {
rlpParse();
return this.receiveAddress == null || Arrays.equals(this.receiveAddress,ByteUtil.EMPTY_BYTE_ARRAY);
}
/*
* Crypto
*/
public ECKey getKey() {
byte[] hash = getRawHash();
return ECKey.recoverFromSignature(signature.v, signature, hash);
}
public synchronized byte[] getSender() {
try {
if (sendAddress == null && getSignature() != null) {
sendAddress = ECKey.signatureToAddress(getRawHash(), getSignature());
}
return sendAddress;
} catch (SignatureException e) {
logger.error(e.getMessage(), e);
}
return null;
}
public Integer getChainId() {
rlpParse();
return chainId == null ? null : (int) chainId;
}
/**
* @deprecated should prefer #sign(ECKey) over this method
*/
public void sign(byte[] privKeyBytes) throws MissingPrivateKeyException {
sign(ECKey.fromPrivate(privKeyBytes));
}
public void sign(ECKey key) throws MissingPrivateKeyException {
this.signature = key.sign(this.getRawHash());
this.rlpEncoded = null;
}
@Override
public String toString() {
return toString(Integer.MAX_VALUE);
}
public String toString(int maxDataSize) {
rlpParse();
String dataS;
if (data == null) {
dataS = "";
} else if (data.length < maxDataSize) {
dataS = ByteUtil.toHexString(data);
} else {
dataS = ByteUtil.toHexString(Arrays.copyOfRange(data, 0, maxDataSize)) +
"... (" + data.length + " bytes)";
}
return "TransactionData [" + "hash=" + ByteUtil.toHexString(hash) +
" nonce=" + ByteUtil.toHexString(nonce) +
", gasPrice=" + ByteUtil.toHexString(gasPrice) +
", gas=" + ByteUtil.toHexString(gasLimit) +
", receiveAddress=" + ByteUtil.toHexString(receiveAddress) +
", sendAddress=" + ByteUtil.toHexString(getSender()) +
", value=" + ByteUtil.toHexString(value) +
", data=" + dataS +
", signatureV=" + (signature == null ? "" : signature.v) +
", signatureR=" + (signature == null ? "" : ByteUtil.toHexString(BigIntegers.asUnsignedByteArray(signature.r))) +
", signatureS=" + (signature == null ? "" : ByteUtil.toHexString(BigIntegers.asUnsignedByteArray(signature.s))) +
"]";
}
/**
* For signatures you have to keep also
* RLP of the transaction without any signature data
*/
public byte[] getEncodedRaw() {
rlpParse();
byte[] rlpRaw;
// parse null as 0 for nonce
byte[] nonce = null;
if (this.nonce == null || this.nonce.length == 1 && this.nonce[0] == 0) {
nonce = RLP.encodeElement(null);
} else {
nonce = RLP.encodeElement(this.nonce);
}
byte[] gasPrice = RLP.encodeElement(this.gasPrice);
byte[] gasLimit = RLP.encodeElement(this.gasLimit);
byte[] receiveAddress = RLP.encodeElement(this.receiveAddress);
byte[] value = RLP.encodeElement(this.value);
byte[] data = RLP.encodeElement(this.data);
// Since EIP-155 use chainId for v
if (chainId == null) {
rlpRaw = RLP.encodeList(nonce, gasPrice, gasLimit, receiveAddress,
value, data);
} else {
byte[] v, r, s;
v = RLP.encodeInt(chainId);
r = RLP.encodeElement(EMPTY_BYTE_ARRAY);
s = RLP.encodeElement(EMPTY_BYTE_ARRAY);
rlpRaw = RLP.encodeList(nonce, gasPrice, gasLimit, receiveAddress,
value, data, v, r, s);
}
return rlpRaw;
}
public synchronized byte[] getEncoded() {
if (rlpEncoded != null) return rlpEncoded;
// parse null as 0 for nonce
byte[] nonce = null;
if (this.nonce == null || this.nonce.length == 1 && this.nonce[0] == 0) {
nonce = RLP.encodeElement(null);
} else {
nonce = RLP.encodeElement(this.nonce);
}
byte[] gasPrice = RLP.encodeElement(this.gasPrice);
byte[] gasLimit = RLP.encodeElement(this.gasLimit);
byte[] receiveAddress = RLP.encodeElement(this.receiveAddress);
byte[] value = RLP.encodeElement(this.value);
byte[] data = RLP.encodeElement(this.data);
byte[] v, r, s;
if (signature != null) {
int encodeV;
if (chainId == null) {
encodeV = signature.v;
} else {
encodeV = signature.v - LOWER_REAL_V;
encodeV += chainId * 2 + CHAIN_ID_INC;
}
v = RLP.encodeInt(encodeV);
r = RLP.encodeElement(BigIntegers.asUnsignedByteArray(signature.r));
s = RLP.encodeElement(BigIntegers.asUnsignedByteArray(signature.s));
} else {
// Since EIP-155 use chainId for v
v = chainId == null ? RLP.encodeElement(EMPTY_BYTE_ARRAY) : RLP.encodeInt(chainId);
r = RLP.encodeElement(EMPTY_BYTE_ARRAY);
s = RLP.encodeElement(EMPTY_BYTE_ARRAY);
}
this.rlpEncoded = RLP.encodeList(nonce, gasPrice, gasLimit,
receiveAddress, value, data, v, r, s);
this.hash = HashUtil.sha3(rlpEncoded);
return rlpEncoded;
}
@Override
public int hashCode() {
byte[] hash = this.getHash();
int hashCode = 0;
for (int i = 0; i < hash.length; ++i) {
hashCode += hash[i] * i;
}
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Transaction)) return false;
Transaction tx = (Transaction) obj;
return tx.hashCode() == this.hashCode();
}
/**
* @deprecated Use {@link Transaction#createDefault(String, BigInteger, BigInteger, Integer)} instead
*/
public static Transaction createDefault(String to, BigInteger amount, BigInteger nonce){
return create(to, amount, nonce, DEFAULT_GAS_PRICE, DEFAULT_BALANCE_GAS);
}
public static Transaction createDefault(String to, BigInteger amount, BigInteger nonce, Integer chainId){
return create(to, amount, nonce, DEFAULT_GAS_PRICE, DEFAULT_BALANCE_GAS, chainId);
}
/**
* @deprecated use {@link Transaction#create(String, BigInteger, BigInteger, BigInteger, BigInteger, Integer)} instead
*/
public static Transaction create(String to, BigInteger amount, BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit){
return new Transaction(BigIntegers.asUnsignedByteArray(nonce),
BigIntegers.asUnsignedByteArray(gasPrice),
BigIntegers.asUnsignedByteArray(gasLimit),
Hex.decode(to),
BigIntegers.asUnsignedByteArray(amount),
null);
}
public static Transaction create(String to, BigInteger amount, BigInteger nonce, BigInteger gasPrice,
BigInteger gasLimit, Integer chainId){
return new Transaction(BigIntegers.asUnsignedByteArray(nonce),
BigIntegers.asUnsignedByteArray(gasPrice),
BigIntegers.asUnsignedByteArray(gasLimit),
Hex.decode(to),
BigIntegers.asUnsignedByteArray(amount),
null,
chainId);
}
public static final MemSizeEstimator<Transaction> MemEstimator = tx ->
ByteArrayEstimator.estimateSize(tx.hash) +
ByteArrayEstimator.estimateSize(tx.nonce) +
ByteArrayEstimator.estimateSize(tx.value) +
ByteArrayEstimator.estimateSize(tx.gasPrice) +
ByteArrayEstimator.estimateSize(tx.gasLimit) +
ByteArrayEstimator.estimateSize(tx.data) +
ByteArrayEstimator.estimateSize(tx.sendAddress) +
ByteArrayEstimator.estimateSize(tx.rlpEncoded) +
ByteArrayEstimator.estimateSize(tx.rawHash) +
(tx.chainId != null ? 24 : 0) +
(tx.signature != null ? 208 : 0) + // approximate size of signature
16; // Object header + ref
}
| 21,216
| 34.900169
| 129
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/Blockchain.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core;
import java.math.BigInteger;
import java.util.Iterator;
import java.util.List;
public interface Blockchain {
long getSize();
BlockSummary add(Block block);
ImportResult tryToConnect(Block block);
void storeBlock(Block block, List<TransactionReceipt> receipts);
Block getBlockByNumber(long blockNr);
void setBestBlock(Block block);
Block getBestBlock();
boolean hasParentOnTheChain(Block block);
void close();
void updateTotalDifficulty(Block block);
BigInteger getTotalDifficulty();
void setTotalDifficulty(BigInteger totalDifficulty);
byte[] getBestBlockHash();
List<byte[]> getListOfHashesStartFrom(byte[] hash, int qty);
List<byte[]> getListOfHashesStartFromBlock(long blockNumber, int qty);
/**
* Returns the transaction info stored in the blockchain
* This doesn't involve pending transactions
* If transaction was included to more than one block (from different forks)
* the method returns TransactionInfo from the block on the main chain.
*/
TransactionInfo getTransactionInfo(byte[] hash);
Block getBlockByHash(byte[] hash);
List<Chain> getAltChains();
List<Block> getGarbage();
void setExitOn(long exitOn);
byte[] getMinerCoinbase();
boolean isBlockExist(byte[] hash);
/**
* @deprecated
* Returns up to limit headers found with following search parameters
* [Synchronized only in blockstore, not using any synchronized BlockchainImpl methods]
* @param identifier Identifier of start block, by number of by hash
* @param skip Number of blocks to skip between consecutive headers
* @param limit Maximum number of headers in return
* @param reverse Is search reverse or not
* @return {@link BlockHeader}'s list or empty list if none found
*/
@Deprecated
List<BlockHeader> getListOfHeadersStartFrom(BlockIdentifier identifier, int skip, int limit, boolean reverse);
/**
* Returns iterator with up to limit headers found with following search parameters
* [Synchronized only in blockstore, not using any synchronized BlockchainImpl methods]
* @param identifier Identifier of start block, by number of by hash
* @param skip Number of blocks to skip between consecutive headers
* @param limit Maximum number of headers in return
* @param reverse Is search reverse or not
* @return {@link BlockHeader}'s iterator
*/
Iterator<BlockHeader> getIteratorOfHeadersStartFrom(BlockIdentifier identifier, int skip, int limit, boolean reverse);
/**
* @deprecated
* Returns list of block bodies by block hashes, stopping on first not found block
* [Synchronized only in blockstore, not using any synchronized BlockchainImpl methods]
* @param hashes List of hashes
* @return List of RLP encoded block bodies
*/
@Deprecated
List<byte[]> getListOfBodiesByHashes(List<byte[]> hashes);
/**
* Returns iterator of block bodies by block hashes, stopping on first not found block
* [Synchronized only in blockstore, not using any synchronized BlockchainImpl methods]
* @param hashes List of hashes
* @return Iterator of RLP encoded block bodies
*/
Iterator<byte[]> getIteratorOfBodiesByHashes(List<byte[]> hashes);
Block createNewBlock(Block parent, List<Transaction> transactions, List<BlockHeader> uncles);
}
| 4,325
| 35.05
| 122
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/EventDispatchThread.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.concurrent.*;
/**
* The class intended to serve as an 'Event Bus' where all EthereumJ events are
* dispatched asynchronously from component to component or from components to
* the user event handlers.
*
* This made for decoupling different components which are intended to work
* asynchronously and to avoid complex synchronisation and deadlocks between them
*
* Created by Anton Nashatyrev on 29.12.2015.
*/
@Component
public class EventDispatchThread {
private static final Logger logger = LoggerFactory.getLogger("blockchain");
private static EventDispatchThread eventDispatchThread;
private static final int[] queueSizeWarnLevels = new int[]{0, 10_000, 50_000, 100_000, 250_000, 500_000, 1_000_000, 10_000_000};
private final BlockingQueue<Runnable> executorQueue = new LinkedBlockingQueue<Runnable>();
private final ExecutorService executor = new ThreadPoolExecutor(1, 1, 0L,
TimeUnit.MILLISECONDS, executorQueue, r -> new Thread(r, "EDT")
);
private long taskStart;
private Runnable lastTask;
private int lastQueueSizeWarnLevel = 0;
private int counter;
/**
* Returns the default instance for initialization of Autowired instances
* to be used in tests
*/
public static EventDispatchThread getDefault() {
if (eventDispatchThread == null) {
eventDispatchThread = new EventDispatchThread() {
@Override
public void invokeLater(Runnable r) {
r.run();
}
};
}
return eventDispatchThread;
}
public void invokeLater(final Runnable r) {
if (executor.isShutdown()) return;
if (counter++ % 1000 == 0) logStatus();
executor.submit(() -> {
try {
lastTask = r;
taskStart = System.nanoTime();
r.run();
long t = (System.nanoTime() - taskStart) / 1_000_000;
taskStart = 0;
if (t > 1000) {
logger.warn("EDT task executed in more than 1 sec: " + t + "ms, " +
"Executor queue size: " + executorQueue.size());
}
} catch (Exception e) {
logger.error("EDT task exception", e);
}
});
}
// monitors EDT queue size and prints warning if exceeds thresholds
private void logStatus() {
int curLevel = getSizeWarnLevel(executorQueue.size());
if (lastQueueSizeWarnLevel == curLevel) return;
synchronized (this) {
if (curLevel > lastQueueSizeWarnLevel) {
long t = taskStart == 0 ? 0 : (System.nanoTime() - taskStart) / 1_000_000;
String msg = "EDT size grown up to " + executorQueue.size() + " (last task executing for " + t + " ms: " + lastTask;
if (curLevel < 3) {
logger.info(msg);
} else {
logger.warn(msg);
}
} else if (curLevel < lastQueueSizeWarnLevel) {
logger.info("EDT size shrunk down to " + executorQueue.size());
}
lastQueueSizeWarnLevel = curLevel;
}
}
private static int getSizeWarnLevel(int size) {
int idx = Arrays.binarySearch(queueSizeWarnLevels, size);
return idx >= 0 ? idx : -(idx + 1) - 1;
}
public void shutdown() {
executor.shutdownNow();
try {
executor.awaitTermination(10L, TimeUnit.SECONDS);
} catch (InterruptedException e) {
logger.warn("shutdown: executor interrupted: {}", e.getMessage());
}
}
}
| 4,646
| 35.590551
| 132
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/genesis/GenesisJson.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core.genesis;
import java.util.Map;
public class GenesisJson {
String mixhash;
String coinbase;
String timestamp;
String parentHash;
String extraData;
String gasLimit;
String nonce;
String difficulty;
Map<String, AllocatedAccount> alloc;
GenesisConfig config;
public GenesisJson() {
}
public String getMixhash() {
return mixhash;
}
public void setMixhash(String mixhash) {
this.mixhash = mixhash;
}
public String getCoinbase() {
return coinbase;
}
public void setCoinbase(String coinbase) {
this.coinbase = coinbase;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getParentHash() {
return parentHash;
}
public void setParentHash(String parentHash) {
this.parentHash = parentHash;
}
public String getExtraData() {
return extraData;
}
public void setExtraData(String extraData) {
this.extraData = extraData;
}
public String getGasLimit() {
return gasLimit;
}
public void setGasLimit(String gasLimit) {
this.gasLimit = gasLimit;
}
public String getNonce() {
return nonce;
}
public void setNonce(String nonce) {
this.nonce = nonce;
}
public String getDifficulty() {
return difficulty;
}
public void setDifficulty(String difficulty) {
this.difficulty = difficulty;
}
public Map<String, AllocatedAccount> getAlloc() {
return alloc;
}
public void setAlloc(Map<String, AllocatedAccount> alloc) {
this.alloc = alloc;
}
public GenesisConfig getConfig() {
return config;
}
public void setConfig(GenesisConfig config) {
this.config = config;
}
public static class AllocatedAccount {
public Map<String, String> storage;
public String nonce;
public String code;
public String balance;
}
}
| 2,919
| 21.461538
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/genesis/GenesisConfig.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core.genesis;
import java.util.List;
/**
* Created by Anton on 03.03.2017.
*/
public class GenesisConfig {
public Integer homesteadBlock;
public Integer daoForkBlock;
public Integer eip150Block;
public Integer eip155Block;
public boolean daoForkSupport;
public Integer eip158Block;
public Integer byzantiumBlock;
public Integer constantinopleBlock;
public Integer petersburgBlock;
public Integer chainId;
// EthereumJ private options
public static class HashValidator {
public long number;
public String hash;
}
public List<HashValidator> headerValidators;
public boolean isCustomConfig() {
return homesteadBlock != null || daoForkBlock != null || eip150Block != null ||
eip155Block != null || eip158Block != null || byzantiumBlock != null ||
constantinopleBlock != null || petersburgBlock != null;
}
}
| 1,742
| 32.519231
| 87
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/core/genesis/GenesisLoader.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core.genesis;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.io.ByteStreams;
import org.ethereum.config.BlockchainNetConfig;
import org.ethereum.config.SystemProperties;
import org.ethereum.core.AccountState;
import org.ethereum.core.Genesis;
import org.ethereum.crypto.HashUtil;
import org.ethereum.db.ByteArrayWrapper;
import org.ethereum.trie.SecureTrie;
import org.ethereum.trie.Trie;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.Utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import static org.ethereum.core.Genesis.ZERO_HASH_2048;
import static org.ethereum.crypto.HashUtil.EMPTY_LIST_HASH;
import static org.ethereum.util.ByteUtil.*;
import static org.ethereum.core.BlockHeader.NONCE_LENGTH;
import static org.ethereum.core.Genesis.PremineAccount;
public class GenesisLoader {
/**
* Load genesis from passed location or from classpath `genesis` directory
*/
public static GenesisJson loadGenesisJson(SystemProperties config, ClassLoader classLoader) throws RuntimeException {
final String genesisFile = config.getProperty("genesisFile", null);
final String genesisResource = config.genesisInfo();
// #1 try to find genesis at passed location
if (genesisFile != null) {
try (InputStream is = new FileInputStream(new File(genesisFile))) {
return loadGenesisJson(is);
} catch (Exception e) {
showLoadError("Problem loading genesis file from " + genesisFile, genesisFile, genesisResource);
}
}
// #2 fall back to old genesis location at `src/main/resources/genesis` directory
InputStream is = classLoader.getResourceAsStream("genesis/" + genesisResource);
if (is != null) {
try {
return loadGenesisJson(is);
} catch (Exception e) {
showLoadError("Problem loading genesis file from resource directory", genesisFile, genesisResource);
}
} else {
showLoadError("Genesis file was not found in resource directory", genesisFile, genesisResource);
}
return null;
}
private static void showLoadError(String message, String genesisFile, String genesisResource) {
Utils.showErrorAndExit(
message,
"Config option 'genesisFile': " + genesisFile,
"Config option 'genesis': " + genesisResource);
}
public static Genesis parseGenesis(BlockchainNetConfig blockchainNetConfig, GenesisJson genesisJson) throws RuntimeException {
try {
Genesis genesis = createBlockForJson(genesisJson);
genesis.setPremine(generatePreMine(blockchainNetConfig, genesisJson.getAlloc()));
byte[] rootHash = generateRootHash(genesis.getPremine());
genesis.setStateRoot(rootHash);
return genesis;
} catch (Exception e) {
e.printStackTrace();
Utils.showErrorAndExit("Problem parsing genesis", e.getMessage());
}
return null;
}
/**
* Method used much in tests.
*/
public static Genesis loadGenesis(InputStream resourceAsStream) {
GenesisJson genesisJson = loadGenesisJson(resourceAsStream);
return parseGenesis(SystemProperties.getDefault().getBlockchainConfig(), genesisJson);
}
public static GenesisJson loadGenesisJson(InputStream genesisJsonIS) throws RuntimeException {
String json = null;
try {
json = new String(ByteStreams.toByteArray(genesisJsonIS));
ObjectMapper mapper = new ObjectMapper()
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES);
GenesisJson genesisJson = mapper.readValue(json, GenesisJson.class);
return genesisJson;
} catch (Exception e) {
Utils.showErrorAndExit("Problem parsing genesis: "+ e.getMessage(), json);
throw new RuntimeException(e.getMessage(), e);
}
}
private static Genesis createBlockForJson(GenesisJson genesisJson) {
byte[] nonce = prepareNonce(ByteUtil.hexStringToBytes(genesisJson.nonce));
byte[] difficulty = hexStringToBytesValidate(genesisJson.difficulty, 32, true);
byte[] mixHash = hexStringToBytesValidate(genesisJson.mixhash, 32, false);
byte[] coinbase = hexStringToBytesValidate(genesisJson.coinbase, 20, false);
byte[] timestampBytes = hexStringToBytesValidate(genesisJson.timestamp, 8, true);
long timestamp = ByteUtil.byteArrayToLong(timestampBytes);
byte[] parentHash = hexStringToBytesValidate(genesisJson.parentHash, 32, false);
byte[] extraData = hexStringToBytesValidate(genesisJson.extraData, 32, true);
byte[] gasLimitBytes = hexStringToBytesValidate(genesisJson.gasLimit, 8, true);
long gasLimit = ByteUtil.byteArrayToLong(gasLimitBytes);
return new Genesis(parentHash, EMPTY_LIST_HASH, coinbase, ZERO_HASH_2048,
difficulty, 0, gasLimit, 0, timestamp, extraData,
mixHash, nonce);
}
private static byte[] hexStringToBytesValidate(String hex, int bytes, boolean notGreater) {
byte[] ret = ByteUtil.hexStringToBytes(hex);
if (notGreater) {
if (ret.length > bytes) {
throw new RuntimeException("Wrong value length: " + hex + ", expected length < " + bytes + " bytes");
}
} else {
if (ret.length != bytes) {
throw new RuntimeException("Wrong value length: " + hex + ", expected length " + bytes + " bytes");
}
}
return ret;
}
/**
* Prepares nonce to be correct length
* @param nonceUnchecked unchecked, user-provided nonce
* @return correct nonce
* @throws RuntimeException when nonce is too long
*/
private static byte[] prepareNonce(byte[] nonceUnchecked) {
if (nonceUnchecked.length > 8) {
throw new RuntimeException(String.format("Invalid nonce, should be %s length", NONCE_LENGTH));
} else if (nonceUnchecked.length == 8) {
return nonceUnchecked;
}
byte[] nonce = new byte[NONCE_LENGTH];
int diff = NONCE_LENGTH - nonceUnchecked.length;
for (int i = diff; i < NONCE_LENGTH; ++i) {
nonce[i] = nonceUnchecked[i - diff];
}
return nonce;
}
private static Map<ByteArrayWrapper, PremineAccount> generatePreMine(BlockchainNetConfig blockchainNetConfig, Map<String, GenesisJson.AllocatedAccount> allocs){
final Map<ByteArrayWrapper, PremineAccount> premine = new HashMap<>();
for (String key : allocs.keySet()){
final byte[] address = hexStringToBytes(key);
final GenesisJson.AllocatedAccount alloc = allocs.get(key);
final PremineAccount state = new PremineAccount();
AccountState accountState = new AccountState(
blockchainNetConfig.getCommonConstants().getInitialNonce(), parseHexOrDec(alloc.balance));
if (alloc.nonce != null) {
accountState = accountState.withNonce(parseHexOrDec(alloc.nonce));
}
if (alloc.code != null) {
final byte[] codeBytes = hexStringToBytes(alloc.code);
accountState = accountState.withCodeHash(HashUtil.sha3(codeBytes));
state.code = codeBytes;
}
state.accountState = accountState;
premine.put(wrap(address), state);
}
return premine;
}
/**
* @param rawValue either hex started with 0x or dec
* return BigInteger
*/
private static BigInteger parseHexOrDec(String rawValue) {
if (rawValue != null) {
return rawValue.startsWith("0x") ? bytesToBigInteger(hexStringToBytes(rawValue)) : new BigInteger(rawValue);
} else {
return BigInteger.ZERO;
}
}
public static byte[] generateRootHash(Map<ByteArrayWrapper, PremineAccount> premine){
Trie<byte[]> state = new SecureTrie((byte[]) null);
for (ByteArrayWrapper key : premine.keySet()) {
state.put(key.getData(), premine.get(key).accountState.getEncoded());
}
return state.getRootHash();
}
}
| 9,538
| 38.580913
| 164
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/config/Constants.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.config;
import org.ethereum.util.blockchain.EtherUtil;
import java.math.BigInteger;
/**
* Describes different constants specific for a blockchain
*
* Created by Anton Nashatyrev on 25.02.2016.
*/
public class Constants {
private static final int MAXIMUM_EXTRA_DATA_SIZE = 32;
private static final int MIN_GAS_LIMIT = 125000;
private static final int GAS_LIMIT_BOUND_DIVISOR = 1024;
private static final BigInteger MINIMUM_DIFFICULTY = BigInteger.valueOf(131072);
private static final BigInteger DIFFICULTY_BOUND_DIVISOR = BigInteger.valueOf(2048);
private static final int EXP_DIFFICULTY_PERIOD = 100000;
private static final int UNCLE_GENERATION_LIMIT = 7;
private static final int UNCLE_LIST_LIMIT = 2;
private static final int BEST_NUMBER_DIFF_LIMIT = 100;
private static final BigInteger BLOCK_REWARD = EtherUtil.convert(1500, EtherUtil.Unit.FINNEY); // 1.5 ETH
private static final BigInteger SECP256K1N = new BigInteger("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", 16);
private static final int LONGEST_CHAIN = 192;
public int getDURATION_LIMIT() {
return 8;
}
public BigInteger getInitialNonce() {
return BigInteger.ZERO;
}
public int getMAXIMUM_EXTRA_DATA_SIZE() {
return MAXIMUM_EXTRA_DATA_SIZE;
}
public int getMIN_GAS_LIMIT() {
return MIN_GAS_LIMIT;
}
public int getGAS_LIMIT_BOUND_DIVISOR() {
return GAS_LIMIT_BOUND_DIVISOR;
}
public BigInteger getMINIMUM_DIFFICULTY() {
return MINIMUM_DIFFICULTY;
}
public BigInteger getDIFFICULTY_BOUND_DIVISOR() {
return DIFFICULTY_BOUND_DIVISOR;
}
public int getEXP_DIFFICULTY_PERIOD() {
return EXP_DIFFICULTY_PERIOD;
}
public int getUNCLE_GENERATION_LIMIT() {
return UNCLE_GENERATION_LIMIT;
}
public int getUNCLE_LIST_LIMIT() {
return UNCLE_LIST_LIMIT;
}
public int getBEST_NUMBER_DIFF_LIMIT() {
return BEST_NUMBER_DIFF_LIMIT;
}
public BigInteger getBLOCK_REWARD() {
return BLOCK_REWARD;
}
public int getMAX_CONTRACT_SZIE() { return Integer.MAX_VALUE; }
/**
* Introduced in the Homestead release
*/
public boolean createEmptyContractOnOOG() {
return true;
}
/**
* New DELEGATECALL opcode introduced in the Homestead release. Before Homestead this opcode should generate
* exception
*/
public boolean hasDelegateCallOpcode() {return false; }
/**
* Introduced in the Homestead release
*/
public static BigInteger getSECP256K1N() {
return SECP256K1N;
}
public static int getLONGEST_CHAIN() {
return LONGEST_CHAIN;
}
}
| 3,572
| 28.286885
| 136
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/config/Initializer.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.config;
import org.ethereum.net.eth.EthVersion;
import org.ethereum.net.shh.ShhHandler;
import org.ethereum.net.swarm.bzz.BzzHandler;
import org.ethereum.util.BuildInfo;
import org.ethereum.util.FileUtil;
import org.ethereum.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import java.io.*;
import java.util.Properties;
/**
* Created by Anton Nashatyrev on 13.05.2016.
*/
class Initializer implements BeanPostProcessor {
private static final Logger logger = LoggerFactory.getLogger("general");
// Util to ensure database directory is compatible with code
private DatabaseVersionHandler databaseVersionHandler = new DatabaseVersionHandler();
/**
* Method to be called right after the config is instantiated.
* Effectively is called before any other bean is initialized
*/
private void initConfig(SystemProperties config) {
logger.info("Running {}, core version: {}-{}", config.genesisInfo(), config.projectVersion(), config.projectVersionModifier());
BuildInfo.printInfo();
databaseVersionHandler.process(config);
if (logger.isInfoEnabled()) {
StringBuilder versions = new StringBuilder();
for (EthVersion v : EthVersion.supported()) {
versions.append(v.getCode()).append(", ");
}
versions.delete(versions.length() - 2, versions.length());
logger.info("capability eth version: [{}]", versions);
}
logger.info("capability shh version: [{}]", ShhHandler.VERSION);
logger.info("capability bzz version: [{}]", BzzHandler.VERSION);
// forcing loading blockchain config
config.getBlockchainConfig();
logger.info("Blockchain config {}", config.getBlockchainConfig().toString());
// forcing loading genesis to fail fast in case of error
config.getGenesis();
// forcing reading private key or generating it in database directory
config.nodeId();
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof SystemProperties) {
initConfig((SystemProperties) bean);
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
/**
* We need to persist the DB version, so after core upgrade we can either reset older incompatible db
* or make a warning and let the user reset DB manually.
* Database version is stored in ${database}/version.properties
* Logic will assume that database has version 1 if file with version is absent.
*/
public static class DatabaseVersionHandler {
public enum Behavior {
EXIT, RESET, IGNORE
}
public void process(SystemProperties config) {
if (config.getKeyValueDataSource().equals("leveldb"))
Utils.showWarn(
"Deprecated database engine detected",
"'leveldb' support will be removed in one of the next releases",
"thus it is strongly recommended to stick with 'rocksdb' instead"
);
if (config.databaseReset() && config.databaseResetBlock() == 0){
FileUtil.recursiveDelete(config.databaseDir());
putDatabaseVersion(config, config.databaseVersion());
logger.info("Database reset done");
System.out.println("Database reset done");
}
final File versionFile = getDatabaseVersionFile(config);
final Behavior behavior = Behavior.valueOf(
config.getProperty("database.incompatibleDatabaseBehavior", Behavior.EXIT.toString()).toUpperCase());
// Detect database version
final Integer expectedVersion = config.databaseVersion();
if (isDatabaseDirectoryExists(config)) {
final Integer actualVersionRaw = getDatabaseVersion(versionFile);
final boolean isVersionFileNotFound = actualVersionRaw.equals(-1);
final Integer actualVersion = isVersionFileNotFound ? 1 : actualVersionRaw;
if (actualVersionRaw.equals(-1)) {
putDatabaseVersion(config, actualVersion);
}
if (actualVersion.equals(expectedVersion) || (isVersionFileNotFound && expectedVersion.equals(1))) {
logger.info("Database directory location: '{}', version: {}", config.databaseDir(), actualVersion);
} else {
logger.warn("Detected incompatible database version. Detected:{}, required:{}", actualVersion, expectedVersion);
if (behavior == Behavior.EXIT) {
Utils.showErrorAndExit(
"Incompatible database version " + actualVersion,
"Please remove database directory manually or set `database.incompatibleDatabaseBehavior` to `RESET`",
"Database directory location is " + config.databaseDir()
);
} else if (behavior == Behavior.RESET) {
boolean res = FileUtil.recursiveDelete(config.databaseDir());
if (!res) {
throw new RuntimeException("Couldn't delete database dir: " + config.databaseDir());
}
putDatabaseVersion(config, config.databaseVersion());
logger.warn("Auto reset database directory according to flag");
} else {
// IGNORE
logger.info("Continue working according to flag");
}
}
} else {
putDatabaseVersion(config, config.databaseVersion());
logger.info("Created database version file");
}
}
public boolean isDatabaseDirectoryExists(SystemProperties config) {
final File databaseFile = new File(config.databaseDir());
return databaseFile.exists() && databaseFile.isDirectory() && databaseFile.list().length > 0;
}
/**
* @return database version stored in specific location in database dir
* or -1 if can't detect version due to error
*/
public Integer getDatabaseVersion(File file) {
if (!file.exists()) {
return -1;
}
try (Reader reader = new FileReader(file)) {
Properties prop = new Properties();
prop.load(reader);
return Integer.valueOf(prop.getProperty("databaseVersion"));
} catch (Exception e) {
logger.error("Problem reading current database version.", e);
return -1;
}
}
public void putDatabaseVersion(SystemProperties config, Integer version) {
final File versionFile = getDatabaseVersionFile(config);
versionFile.getParentFile().mkdirs();
try (Writer writer = new FileWriter(versionFile)) {
Properties prop = new Properties();
prop.setProperty("databaseVersion", version.toString());
prop.store(writer, "Generated database version");
} catch (Exception e) {
throw new Error("Problem writing current database version ", e);
}
}
private File getDatabaseVersionFile(SystemProperties config) {
return new File(config.databaseDir() + "/version.properties");
}
}
}
| 8,724
| 42.193069
| 136
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/config/DefaultConfig.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.config;
import org.ethereum.datasource.Source;
import org.ethereum.db.BlockStore;
import org.ethereum.db.IndexedBlockStore;
import org.ethereum.db.PruneManager;
import org.ethereum.db.TransactionStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.FatalBeanException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import java.util.List;
import static java.util.Arrays.asList;
/**
*
* @author Roman Mandeleil
* Created on: 27/01/2015 01:05
*/
@Configuration
@Import(CommonConfig.class)
public class DefaultConfig {
private static Logger logger = LoggerFactory.getLogger("general");
@Autowired
ApplicationContext appCtx;
@Autowired
CommonConfig commonConfig;
@Autowired
SystemProperties config;
private final static List<Class<? extends Exception>> FATAL_EXCEPTIONS = asList(FatalBeanException.class);
public DefaultConfig() {
Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
logger.error("Uncaught exception", e);
FATAL_EXCEPTIONS.stream()
.filter(errType -> errType.isInstance(e))
.findFirst()
.ifPresent(errType -> System.exit(1));
});
}
@Bean
public BlockStore blockStore(){
commonConfig.fastSyncCleanUp();
IndexedBlockStore indexedBlockStore = new IndexedBlockStore();
Source<byte[], byte[]> block = commonConfig.cachedDbSource("block");
Source<byte[], byte[]> index = commonConfig.cachedDbSource("index");
indexedBlockStore.init(index, block);
return indexedBlockStore;
}
@Bean
public TransactionStore transactionStore() {
commonConfig.fastSyncCleanUp();
return new TransactionStore(commonConfig.cachedDbSource("transactions"));
}
@Bean
public PruneManager pruneManager() {
if (config.databasePruneDepth() >= 0) {
return new PruneManager((IndexedBlockStore) blockStore(), commonConfig.stateSource().getJournalSource(),
commonConfig.stateSource().getNoJournalSource(), config.databasePruneDepth());
} else {
return new PruneManager(null, null, null, -1); // dummy
}
}
}
| 3,297
| 33.354167
| 116
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/config/ConstantsAdapter.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.config;
import java.math.BigInteger;
/**
* Created by Anton Nashatyrev on 15.11.2016.
*/
public class ConstantsAdapter extends Constants {
private final Constants delegate;
public ConstantsAdapter(Constants delegate) {
this.delegate = delegate;
}
@Override
public int getDURATION_LIMIT() {
return delegate.getDURATION_LIMIT();
}
@Override
public BigInteger getInitialNonce() {
return delegate.getInitialNonce();
}
@Override
public int getMAXIMUM_EXTRA_DATA_SIZE() {
return delegate.getMAXIMUM_EXTRA_DATA_SIZE();
}
@Override
public int getMIN_GAS_LIMIT() {
return delegate.getMIN_GAS_LIMIT();
}
@Override
public int getGAS_LIMIT_BOUND_DIVISOR() {
return delegate.getGAS_LIMIT_BOUND_DIVISOR();
}
@Override
public BigInteger getMINIMUM_DIFFICULTY() {
return delegate.getMINIMUM_DIFFICULTY();
}
@Override
public BigInteger getDIFFICULTY_BOUND_DIVISOR() {
return delegate.getDIFFICULTY_BOUND_DIVISOR();
}
@Override
public int getEXP_DIFFICULTY_PERIOD() {
return delegate.getEXP_DIFFICULTY_PERIOD();
}
@Override
public int getUNCLE_GENERATION_LIMIT() {
return delegate.getUNCLE_GENERATION_LIMIT();
}
@Override
public int getUNCLE_LIST_LIMIT() {
return delegate.getUNCLE_LIST_LIMIT();
}
@Override
public int getBEST_NUMBER_DIFF_LIMIT() {
return delegate.getBEST_NUMBER_DIFF_LIMIT();
}
@Override
public BigInteger getBLOCK_REWARD() {
return delegate.getBLOCK_REWARD();
}
@Override
public int getMAX_CONTRACT_SZIE() {
return delegate.getMAX_CONTRACT_SZIE();
}
@Override
public boolean createEmptyContractOnOOG() {
return delegate.createEmptyContractOnOOG();
}
@Override
public boolean hasDelegateCallOpcode() {
return delegate.hasDelegateCallOpcode();
}
public static BigInteger getSECP256K1N() {
return Constants.getSECP256K1N();
}
}
| 2,894
| 25.081081
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/config/CommonConfig.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.config;
import org.ethereum.core.Repository;
import org.ethereum.crypto.HashUtil;
import org.ethereum.datasource.*;
import org.ethereum.datasource.inmem.HashMapDB;
import org.ethereum.datasource.leveldb.LevelDbDataSource;
import org.ethereum.datasource.rocksdb.RocksDbDataSource;
import org.ethereum.db.*;
import org.ethereum.listener.CompositeEthereumListener;
import org.ethereum.listener.EthereumListener;
import org.ethereum.net.eth.handler.Eth63;
import org.ethereum.sync.FastSyncManager;
import org.ethereum.validator.*;
import org.ethereum.vm.DataWord;
import org.ethereum.vm.program.ProgramPrecompile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static java.util.Arrays.asList;
@Configuration
@ComponentScan(
basePackages = "org.ethereum",
excludeFilters = @ComponentScan.Filter(NoAutoscan.class))
public class CommonConfig {
private static final Logger logger = LoggerFactory.getLogger("general");
private Set<DbSource> dbSources = new HashSet<>();
private static CommonConfig defaultInstance;
public static CommonConfig getDefault() {
if (defaultInstance == null && !SystemProperties.isUseOnlySpringConfig()) {
defaultInstance = new CommonConfig() {
@Override
public Source<byte[], ProgramPrecompile> precompileSource() {
return null;
}
};
}
return defaultInstance;
}
@Bean
public SystemProperties systemProperties() {
return SystemProperties.getSpringDefault();
}
@Bean
BeanPostProcessor initializer() {
return new Initializer();
}
@Bean @Primary
public Repository repository() {
return new RepositoryWrapper();
}
@Bean
public Repository defaultRepository() {
return new RepositoryRoot(stateSource(), null);
}
@Bean @Scope("prototype")
public Repository repository(byte[] stateRoot) {
return new RepositoryRoot(stateSource(), stateRoot);
}
/**
* A source of nodes for state trie and all contract storage tries. <br/>
* This source provides contract code too. <br/><br/>
*
* Picks node by 16-bytes prefix of its key. <br/>
* Within {@link NodeKeyCompositor} this source is a part of ref counting workaround<br/><br/>
*
* <b>Note:</b> is eligible as a public node provider, like in {@link Eth63};
* {@link StateSource} is intended for inner usage only
*
* @see NodeKeyCompositor
* @see RepositoryRoot#RepositoryRoot(Source, byte[])
* @see Eth63
*/
@Bean
public Source<byte[], byte[]> trieNodeSource() {
DbSource<byte[]> db = blockchainDB();
Source<byte[], byte[]> src = new PrefixLookupSource<>(db, NodeKeyCompositor.PREFIX_BYTES);
return new XorDataSource<>(src, HashUtil.sha3("state".getBytes()));
}
@Bean
public StateSource stateSource() {
fastSyncCleanUp();
StateSource stateSource = new StateSource(blockchainSource("state"),
systemProperties().databasePruneDepth() >= 0);
dbFlushManager().addCache(stateSource.getWriteCache());
return stateSource;
}
@Bean
@Scope("prototype")
public Source<byte[], byte[]> cachedDbSource(String name) {
AbstractCachedSource<byte[], byte[]> writeCache = new AsyncWriteCache<byte[], byte[]>(blockchainSource(name)) {
@Override
protected WriteCache<byte[], byte[]> createCache(Source<byte[], byte[]> source) {
WriteCache.BytesKey<byte[]> ret = new WriteCache.BytesKey<>(source, WriteCache.CacheType.SIMPLE);
ret.withSizeEstimators(MemSizeEstimator.ByteArrayEstimator, MemSizeEstimator.ByteArrayEstimator);
ret.setFlushSource(true);
return ret;
}
}.withName(name);
dbFlushManager().addCache(writeCache);
return writeCache;
}
@Bean
@Scope("prototype")
public Source<byte[], byte[]> blockchainSource(String name) {
return new XorDataSource<>(blockchainDbCache(), HashUtil.sha3(name.getBytes()));
}
@Bean
public AbstractCachedSource<byte[], byte[]> blockchainDbCache() {
WriteCache.BytesKey<byte[]> ret = new WriteCache.BytesKey<>(
new BatchSourceWriter<>(blockchainDB()), WriteCache.CacheType.SIMPLE);
ret.setFlushSource(true);
return ret;
}
public DbSource<byte[]> keyValueDataSource(String name) {
return keyValueDataSource(name, DbSettings.DEFAULT);
}
@Bean
@Scope("prototype")
@Primary
public DbSource<byte[]> keyValueDataSource(String name, DbSettings settings) {
String dataSource = systemProperties().getKeyValueDataSource();
try {
DbSource<byte[]> dbSource;
if ("inmem".equals(dataSource)) {
dbSource = new HashMapDB<>();
} else if ("leveldb".equals(dataSource)){
dbSource = levelDbDataSource();
} else {
dataSource = "rocksdb";
dbSource = rocksDbDataSource();
}
dbSource.setName(name);
dbSource.init(settings);
dbSources.add(dbSource);
return dbSource;
} finally {
logger.info(dataSource + " key-value data source created: " + name);
}
}
@Bean
@Scope("prototype")
protected LevelDbDataSource levelDbDataSource() {
return new LevelDbDataSource();
}
@Bean
@Scope("prototype")
protected RocksDbDataSource rocksDbDataSource() {
return new RocksDbDataSource();
}
public void fastSyncCleanUp() {
if (!systemProperties().isSyncEnabled()) return;
byte[] fastsyncStageBytes = blockchainDB().get(FastSyncManager.FASTSYNC_DB_KEY_SYNC_STAGE);
if (fastsyncStageBytes == null) return; // no uncompleted fast sync
if (!systemProperties().blocksLoader().isEmpty()) return; // blocks loader enabled
EthereumListener.SyncState syncStage = EthereumListener.SyncState.values()[fastsyncStageBytes[0]];
if (!systemProperties().isFastSyncEnabled() || syncStage == EthereumListener.SyncState.UNSECURE) {
// we need to cleanup state/blocks/tranasaction DBs when previous fast sync was not complete:
// - if we now want to do regular sync
// - if the first fastsync stage was not complete (thus DBs are not in consistent state)
logger.warn("Last fastsync was interrupted. Removing inconsistent DBs...");
DbSource bcSource = blockchainDB();
resetDataSource(bcSource);
}
}
private void resetDataSource(Source source) {
if (source instanceof DbSource) {
((DbSource) source).reset();
} else {
throw new Error("Cannot cleanup non-db Source");
}
}
@Bean(name = "EthereumListener")
public CompositeEthereumListener ethereumListener() {
return new CompositeEthereumListener();
}
@Bean
@Lazy
public DbSource<byte[]> headerSource() {
return keyValueDataSource("headers");
}
@Bean
@Lazy
public HeaderStore headerStore() {
DbSource<byte[]> dataSource = headerSource();
WriteCache.BytesKey<byte[]> cache = new WriteCache.BytesKey<>(
new BatchSourceWriter<>(dataSource), WriteCache.CacheType.SIMPLE);
cache.setFlushSource(true);
dbFlushManager().addCache(cache);
HeaderStore headerStore = new HeaderStore();
Source<byte[], byte[]> headers = new XorDataSource<>(cache, HashUtil.sha3("header".getBytes()));
Source<byte[], byte[]> index = new XorDataSource<>(cache, HashUtil.sha3("index".getBytes()));
headerStore.init(index, headers);
return headerStore;
}
@Bean
public Source<byte[], ProgramPrecompile> precompileSource() {
StateSource source = stateSource();
return new SourceCodec<byte[], ProgramPrecompile, byte[], byte[]>(source,
new Serializer<byte[], byte[]>() {
public byte[] serialize(byte[] object) {
DataWord ret = DataWord.of(object);
DataWord addResult = ret.add(DataWord.ONE);
return addResult.getLast20Bytes();
}
public byte[] deserialize(byte[] stream) {
throw new RuntimeException("Shouldn't be called");
}
}, new Serializer<ProgramPrecompile, byte[]>() {
public byte[] serialize(ProgramPrecompile object) {
return object == null ? null : object.serialize();
}
public ProgramPrecompile deserialize(byte[] stream) {
return stream == null ? null : ProgramPrecompile.deserialize(stream);
}
});
}
@Bean
public DbSource<byte[]> blockchainDB() {
DbSettings settings = DbSettings.newInstance()
.withMaxOpenFiles(systemProperties().getConfig().getInt("database.maxOpenFiles"))
.withMaxThreads(Math.max(1, Runtime.getRuntime().availableProcessors() / 2));
return keyValueDataSource("blockchain", settings);
}
@Bean
public DbFlushManager dbFlushManager() {
return new DbFlushManager(systemProperties(), dbSources, blockchainDbCache());
}
@Bean
public BlockHeaderValidator headerValidator() {
List<BlockHeaderRule> rules = new ArrayList<>(asList(
new GasValueRule(),
new ExtraDataRule(systemProperties()),
EthashRule.createRegular(systemProperties(), ethereumListener()),
new GasLimitRule(systemProperties()),
new BlockHashRule(systemProperties())
));
return new BlockHeaderValidator(rules);
}
@Bean
public ParentBlockHeaderValidator parentHeaderValidator() {
List<DependentBlockHeaderRule> rules = new ArrayList<>(asList(
new ParentNumberRule(),
new DifficultyRule(systemProperties()),
new ParentGasLimitRule(systemProperties())
));
return new ParentBlockHeaderValidator(rules);
}
@Bean
@Lazy
public PeerSource peerSource() {
DbSource<byte[]> dbSource = keyValueDataSource("peers");
dbSources.add(dbSource);
return new PeerSource(dbSource);
}
}
| 11,628
| 34.781538
| 120
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/config/NoAutoscan.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.config;
/**
* Indicates that the Bean/Component/Config shouldn't be picked up automatically by
* Spring config autoscan mechanism
* Created by Anton Nashatyrev on 08.10.2015.
*/
public @interface NoAutoscan {
}
| 1,027
| 37.074074
| 83
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/config/BlockchainConfig.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.config;
import org.apache.commons.lang3.tuple.Pair;
import org.ethereum.core.*;
import org.ethereum.db.BlockStore;
import org.ethereum.mine.MinerIfc;
import org.ethereum.validator.BlockHeaderValidator;
import org.ethereum.vm.DataWord;
import org.ethereum.vm.GasCost;
import org.ethereum.vm.OpCode;
import org.ethereum.vm.program.Program;
import java.math.BigInteger;
import java.util.List;
/**
* Describes constants and algorithms used for a specific blockchain at specific stage
*
* Created by Anton Nashatyrev on 25.02.2016.
*/
public interface BlockchainConfig {
/**
* Get blockchain constants
*/
Constants getConstants();
/**
* Returns the mining algorithm
*/
MinerIfc getMineAlgorithm(SystemProperties config);
/**
* Calculates the difficulty for the block depending on the parent
*/
BigInteger calcDifficulty(BlockHeader curBlock, BlockHeader parent);
/**
* Calculates difficulty adjustment to target mean block time
*/
BigInteger getCalcDifficultyMultiplier(BlockHeader curBlock, BlockHeader parent);
/**
* Calculates transaction gas fee
*/
long getTransactionCost(Transaction tx);
/**
* Validates Tx signature (introduced in Homestead)
*/
boolean acceptTransactionSignature(Transaction tx);
/**
* Validates transaction by the changes made by it in the repository
* @param blockStore
* @param curBlock The block being imported
* @param repositoryTrack The repository track changed by transaction
* @return null if all is fine or String validation error
*/
String validateTransactionChanges(BlockStore blockStore, Block curBlock, Transaction tx,
Repository repositoryTrack);
/**
* Prior to block processing performs some repository manipulations according
* to HardFork rules.
* This method is normally executes the logic on a specific hardfork block only
* for other blocks it just does nothing
*/
void hardForkTransfers(Block block, Repository repo);
/**
* DAO hard fork marker
*/
byte[] getExtraData(byte[] minerExtraData, long blockNumber);
/**
* Fork related validators. Ensure that connected peer operates on the same fork with us
* For example: DAO config will have validator that checks presence of extra data in specific block
*/
List<Pair<Long, BlockHeaderValidator>> headerValidators();
/**
* EVM operations costs
*/
GasCost getGasCost();
/**
* Calculates available gas to be passed for callee
* Since EIP150
* @param op Opcode
* @param requestedGas amount of gas requested by the program
* @param availableGas available gas
* @throws Program.OutOfGasException If passed args doesn't conform to limitations
*/
DataWord getCallGas(OpCode op, DataWord requestedGas, DataWord availableGas) throws Program.OutOfGasException;
/**
* Calculates available gas to be passed for contract constructor
* Since EIP150
*/
DataWord getCreateGas(DataWord availableGas);
/**
* EIP161: https://github.com/ethereum/EIPs/issues/161
*/
boolean eip161();
/**
* EIP155: https://github.com/ethereum/EIPs/issues/155
*/
Integer getChainId();
/**
* EIP198: https://github.com/ethereum/EIPs/pull/198
*/
boolean eip198();
/**
* EIP206: https://github.com/ethereum/EIPs/pull/206
*/
boolean eip206();
/**
* EIP211: https://github.com/ethereum/EIPs/pull/211
*/
boolean eip211();
/**
* EIP212: https://github.com/ethereum/EIPs/pull/212
*/
boolean eip212();
/**
* EIP213: https://github.com/ethereum/EIPs/pull/213
*/
boolean eip213();
/**
* EIP214: https://github.com/ethereum/EIPs/pull/214
*/
boolean eip214();
/**
* EIP658: https://github.com/ethereum/EIPs/pull/658
* Replaces the intermediate state root field of the receipt with the status
*/
boolean eip658();
/**
* EIP145: https://eips.ethereum.org/EIPS/eip-145
* Bitwise shifting instructions in EVM
*/
boolean eip145();
/**
* EIP1052: https://eips.ethereum.org/EIPS/eip-1052
* EXTCODEHASH opcode
*/
boolean eip1052();
/**
* EIP 1283: https://eips.ethereum.org/EIPS/eip-1283
* Net gas metering for SSTORE without dirty maps
*/
boolean eip1283();
/**
* EIP 1014: https://eips.ethereum.org/EIPS/eip-1014
* Skinny CREATE2: same as CREATE but with deterministic address
*/
boolean eip1014();
}
| 5,477
| 27.680628
| 114
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/config/SystemProperties.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.config;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigObject;
import com.typesafe.config.ConfigRenderOptions;
import org.apache.commons.lang3.tuple.Pair;
import org.ethereum.config.blockchain.OlympicConfig;
import org.ethereum.config.net.*;
import org.ethereum.core.Genesis;
import org.ethereum.core.genesis.GenesisConfig;
import org.ethereum.core.genesis.GenesisJson;
import org.ethereum.core.genesis.GenesisLoader;
import org.ethereum.crypto.ECKey;
import org.ethereum.net.p2p.P2pHandler;
import org.ethereum.net.rlpx.MessageCodec;
import org.ethereum.net.rlpx.Node;
import org.ethereum.util.BuildInfo;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.Utils;
import org.ethereum.validator.BlockCustomHashRule;
import org.ethereum.validator.BlockHeaderValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex;
import java.io.*;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
import java.util.*;
import java.util.function.Function;
import static org.ethereum.crypto.HashUtil.sha3;
import static org.ethereum.util.ByteUtil.toHexString;
/**
* Utility class to retrieve property values from the ethereumj.conf files
*
* The properties are taken from different sources and merged in the following order
* (the config option from the next source overrides option from previous):
* - resource ethereumj.conf : normally used as a reference config with default values
* and shouldn't be changed
* - system property : each config entry might be altered via -D VM option
* - [user dir]/config/ethereumj.conf
* - config specified with the -Dethereumj.conf.file=[file.conf] VM option
* - CLI options
*
* @author Roman Mandeleil
* @since 22.05.2014
*/
public class SystemProperties {
private static Logger logger = LoggerFactory.getLogger("general");
public final static String PROPERTY_DB_DIR = "database.dir";
public final static String PROPERTY_LISTEN_PORT = "peer.listen.port";
public final static String PROPERTY_PEER_ACTIVE = "peer.active";
public final static String PROPERTY_DB_RESET = "database.reset";
public final static String PROPERTY_PEER_DISCOVERY_ENABLED = "peer.discovery.enabled";
/* Testing */
private final static Boolean DEFAULT_VMTEST_LOAD_LOCAL = false;
private final static String DEFAULT_BLOCKS_LOADER = "";
private static SystemProperties CONFIG;
private static boolean useOnlySpringConfig = false;
private String generatedNodePrivateKey;
/**
* Returns the static config instance. If the config is passed
* as a Spring bean by the application this instance shouldn't
* be used
* This method is mainly used for testing purposes
* (Autowired fields are initialized with this static instance
* but when running within Spring context they replaced with the
* bean config instance)
*/
public static SystemProperties getDefault() {
return useOnlySpringConfig ? null : getSpringDefault();
}
static SystemProperties getSpringDefault() {
if (CONFIG == null) {
CONFIG = new SystemProperties();
}
return CONFIG;
}
public static void resetToDefault() {
CONFIG = null;
}
/**
* Used mostly for testing purposes to ensure the application
* refers only to the config passed as a Spring bean.
* If this property is set to true {@link #getDefault()} returns null
*/
public static void setUseOnlySpringConfig(boolean useOnlySpringConfig) {
SystemProperties.useOnlySpringConfig = useOnlySpringConfig;
}
static boolean isUseOnlySpringConfig() {
return useOnlySpringConfig;
}
/**
* Marks config accessor methods which need to be called (for value validation)
* upon config creation or modification
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
private @interface ValidateMe {};
private Config config;
// mutable options for tests
private String databaseDir = null;
private Boolean databaseReset = null;
private String projectVersion = null;
private String projectVersionModifier = null;
protected Integer databaseVersion = null;
private String genesisInfo = null;
private String bindIp = null;
private String externalIp = null;
private Boolean syncEnabled = null;
private Boolean discoveryEnabled = null;
private GenesisJson genesisJson;
private BlockchainNetConfig blockchainConfig;
private Genesis genesis;
private Boolean vmTrace;
private Boolean recordInternalTransactionsData;
private final ClassLoader classLoader;
private GenerateNodeIdStrategy generateNodeIdStrategy = null;
public SystemProperties() {
this(ConfigFactory.empty());
}
public SystemProperties(File configFile) {
this(ConfigFactory.parseFile(configFile));
}
public SystemProperties(String configResource) {
this(ConfigFactory.parseResources(configResource));
}
public SystemProperties(Config apiConfig) {
this(apiConfig, SystemProperties.class.getClassLoader());
}
public SystemProperties(Config apiConfig, ClassLoader classLoader) {
try {
this.classLoader = classLoader;
Config javaSystemProperties = ConfigFactory.load("no-such-resource-only-system-props");
Config referenceConfig = ConfigFactory.parseResources("ethereumj.conf");
logger.info("Config (" + (referenceConfig.entrySet().size() > 0 ? " yes " : " no ") + "): default properties from resource 'ethereumj.conf'");
String res = System.getProperty("ethereumj.conf.res");
Config cmdLineConfigRes = mergeConfigs(res, ConfigFactory::parseResources);
logger.info("Config (" + (cmdLineConfigRes.entrySet().size() > 0 ? " yes " : " no ") + "): user properties from -Dethereumj.conf.res resource(s) '" + res + "'");
Config userConfig = ConfigFactory.parseResources("user.conf");
logger.info("Config (" + (userConfig.entrySet().size() > 0 ? " yes " : " no ") + "): user properties from resource 'user.conf'");
File userDirFile = new File(System.getProperty("user.dir"), "/config/ethereumj.conf");
Config userDirConfig = ConfigFactory.parseFile(userDirFile);
logger.info("Config (" + (userDirConfig.entrySet().size() > 0 ? " yes " : " no ") + "): user properties from file '" + userDirFile + "'");
Config testConfig = ConfigFactory.parseResources("test-ethereumj.conf");
logger.info("Config (" + (testConfig.entrySet().size() > 0 ? " yes " : " no ") + "): test properties from resource 'test-ethereumj.conf'");
Config testUserConfig = ConfigFactory.parseResources("test-user.conf");
logger.info("Config (" + (testUserConfig.entrySet().size() > 0 ? " yes " : " no ") + "): test properties from resource 'test-user.conf'");
String file = System.getProperty("ethereumj.conf.file");
Config cmdLineConfigFile = mergeConfigs(file, s -> ConfigFactory.parseFile(new File(s)));
logger.info("Config (" + (cmdLineConfigFile.entrySet().size() > 0 ? " yes " : " no ") + "): user properties from -Dethereumj.conf.file file(s) '" + file + "'");
logger.info("Config (" + (apiConfig.entrySet().size() > 0 ? " yes " : " no ") + "): config passed via constructor");
config = apiConfig
.withFallback(cmdLineConfigFile)
.withFallback(testUserConfig)
.withFallback(testConfig)
.withFallback(userDirConfig)
.withFallback(userConfig)
.withFallback(cmdLineConfigRes)
.withFallback(referenceConfig);
logger.debug("Config trace: " + config.root().render(ConfigRenderOptions.defaults().
setComments(false).setJson(false)));
config = javaSystemProperties.withFallback(config)
.resolve(); // substitute variables in config if any
validateConfig();
// There could be several files with the same name from other packages,
// "version.properties" is a very common name
List<InputStream> iStreams = loadResources("version.properties", this.getClass().getClassLoader());
for (InputStream is : iStreams) {
Properties props = new Properties();
props.load(is);
if (props.getProperty("versionNumber") == null || props.getProperty("databaseVersion") == null) {
continue;
}
this.projectVersion = props.getProperty("versionNumber");
this.projectVersion = this.projectVersion.replaceAll("'", "");
if (this.projectVersion == null) this.projectVersion = "-.-.-";
this.projectVersionModifier = "master".equals(BuildInfo.buildBranch) ? "RELEASE" : "SNAPSHOT";
this.databaseVersion = Integer.valueOf(props.getProperty("databaseVersion"));
this.generateNodeIdStrategy = new GetNodeIdFromPropsFile(databaseDir())
.withFallback(new GenerateNodeIdRandomly(databaseDir()));
break;
}
} catch (Exception e) {
logger.error("Can't read config.", e);
throw new RuntimeException(e);
}
}
/**
* Loads resources using given ClassLoader assuming, there could be several resources
* with the same name
*/
public static List<InputStream> loadResources(
final String name, final ClassLoader classLoader) throws IOException {
final List<InputStream> list = new ArrayList<InputStream>();
final Enumeration<URL> systemResources =
(classLoader == null ? ClassLoader.getSystemClassLoader() : classLoader)
.getResources(name);
while (systemResources.hasMoreElements()) {
list.add(systemResources.nextElement().openStream());
}
return list;
}
public Config getConfig() {
return config;
}
/**
* Puts a new config atop of existing stack making the options
* in the supplied config overriding existing options
* Once put this config can't be removed
*
* @param overrideOptions - atop config
*/
public void overrideParams(Config overrideOptions) {
config = overrideOptions.withFallback(config);
validateConfig();
}
/**
* Puts a new config atop of existing stack making the options
* in the supplied config overriding existing options
* Once put this config can't be removed
*
* @param keyValuePairs [name] [value] [name] [value] ...
*/
public void overrideParams(String ... keyValuePairs) {
if (keyValuePairs.length % 2 != 0) throw new RuntimeException("Odd argument number");
Map<String, String> map = new HashMap<>();
for (int i = 0; i < keyValuePairs.length; i += 2) {
map.put(keyValuePairs[i], keyValuePairs[i + 1]);
}
overrideParams(map);
}
/**
* Puts a new config atop of existing stack making the options
* in the supplied config overriding existing options
* Once put this config can't be removed
*
* @param cliOptions - command line options to take presidency
*/
public void overrideParams(Map<String, ?> cliOptions) {
Config cliConf = ConfigFactory.parseMap(cliOptions);
overrideParams(cliConf);
}
private void validateConfig() {
for (Method method : getClass().getMethods()) {
try {
if (method.isAnnotationPresent(ValidateMe.class)) {
method.invoke(this);
}
} catch (Exception e) {
throw new RuntimeException("Error validating config method: " + method, e);
}
}
}
/**
* Builds config from the list of config references in string doing following actions:
* 1) Splits input by "," to several strings
* 2) Uses parserFunc to create config from each string reference
* 3) Merges configs, applying them in the same order as in input, so last overrides first
* @param input String with list of config references separated by ",", null or one reference works fine
* @param parserFunc Function to apply to each reference, produces config from it
* @return Merged config
*/
protected Config mergeConfigs(String input, Function<String, Config> parserFunc) {
Config config = ConfigFactory.empty();
if (input != null && !input.isEmpty()) {
String[] list = input.split(",");
for (int i = list.length - 1; i >= 0; --i) {
config = config.withFallback(parserFunc.apply(list[i]));
}
}
return config;
}
public <T> T getProperty(String propName, T defaultValue) {
if (!config.hasPath(propName)) return defaultValue;
String string = config.getString(propName);
if (string.trim().isEmpty()) return defaultValue;
return (T) config.getAnyRef(propName);
}
public BlockchainNetConfig getBlockchainConfig() {
if (blockchainConfig == null) {
GenesisJson genesisJson = getGenesisJson();
if (genesisJson.getConfig() != null && genesisJson.getConfig().isCustomConfig()) {
blockchainConfig = new JsonNetConfig(genesisJson.getConfig());
} else {
if (config.hasPath("blockchain.config.name") && config.hasPath("blockchain.config.class")) {
throw new RuntimeException("Only one of two options should be defined: 'blockchain.config.name' and 'blockchain.config.class'");
}
if (config.hasPath("blockchain.config.name")) {
switch (config.getString("blockchain.config.name")) {
case "main":
blockchainConfig = new MainNetConfig();
break;
case "olympic":
blockchainConfig = new OlympicConfig();
break;
case "morden":
blockchainConfig = new MordenNetConfig();
break;
case "ropsten":
blockchainConfig = new RopstenNetConfig();
break;
case "testnet":
blockchainConfig = new TestNetConfig();
break;
default:
throw new RuntimeException("Unknown value for 'blockchain.config.name': '" + config.getString("blockchain.config.name") + "'");
}
} else {
String className = config.getString("blockchain.config.class");
try {
Class<? extends BlockchainNetConfig> aClass = (Class<? extends BlockchainNetConfig>) classLoader.loadClass(className);
blockchainConfig = aClass.newInstance();
} catch (ClassNotFoundException e) {
throw new RuntimeException("The class specified via blockchain.config.class '" + className + "' not found", e);
} catch (ClassCastException e) {
throw new RuntimeException("The class specified via blockchain.config.class '" + className + "' is not instance of org.ethereum.config.BlockchainForkConfig", e);
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException("The class specified via blockchain.config.class '" + className + "' couldn't be instantiated (check for default constructor and its accessibility)", e);
}
}
}
if (genesisJson.getConfig() != null && genesisJson.getConfig().headerValidators != null) {
for (GenesisConfig.HashValidator validator : genesisJson.getConfig().headerValidators) {
BlockHeaderValidator headerValidator = new BlockHeaderValidator(new BlockCustomHashRule(ByteUtil.hexStringToBytes(validator.hash)));
blockchainConfig.getConfigForBlock(validator.number).headerValidators().add(
Pair.of(validator.number, headerValidator));
}
}
}
return blockchainConfig;
}
public void setBlockchainConfig(BlockchainNetConfig config) {
blockchainConfig = config;
}
@ValidateMe
public boolean peerDiscovery() {
return discoveryEnabled == null ? config.getBoolean("peer.discovery.enabled") : discoveryEnabled;
}
public void setDiscoveryEnabled(Boolean discoveryEnabled) {
this.discoveryEnabled = discoveryEnabled;
}
@ValidateMe
public boolean peerDiscoveryPersist() {
return config.getBoolean("peer.discovery.persist");
}
@ValidateMe
public int peerDiscoveryWorkers() {
return config.getInt("peer.discovery.workers");
}
@ValidateMe
public int peerDiscoveryTouchPeriod() {
return config.getInt("peer.discovery.touchPeriod");
}
@ValidateMe
public int peerDiscoveryTouchMaxNodes() {
return config.getInt("peer.discovery.touchMaxNodes");
}
@ValidateMe
public int peerConnectionTimeout() {
return config.getInt("peer.connection.timeout") * 1000;
}
@ValidateMe
public int defaultP2PVersion() {
return config.hasPath("peer.p2p.version") ? config.getInt("peer.p2p.version") : P2pHandler.VERSION;
}
@ValidateMe
public int rlpxMaxFrameSize() {
return config.hasPath("peer.p2p.framing.maxSize") ? config.getInt("peer.p2p.framing.maxSize") : MessageCodec.NO_FRAMING;
}
@ValidateMe
public int transactionApproveTimeout() {
return config.getInt("transaction.approve.timeout") * 1000;
}
@ValidateMe
public List<String> peerDiscoveryIPList() {
return config.getStringList("peer.discovery.ip.list");
}
@ValidateMe
public boolean databaseReset() {
return databaseReset == null ? config.getBoolean("database.reset") : databaseReset;
}
public void setDatabaseReset(Boolean reset) {
databaseReset = reset;
}
@ValidateMe
public long databaseResetBlock() {
return config.getLong("database.resetBlock");
}
@ValidateMe
public boolean databaseFromBackup() {
return config.getBoolean("database.fromBackup");
}
@ValidateMe
public int databasePruneDepth() {
return config.getBoolean("database.prune.enabled") ? config.getInt("database.prune.maxDepth") : -1;
}
@ValidateMe
public List<Node> peerActive() {
if (!config.hasPath("peer.active")) {
return Collections.EMPTY_LIST;
}
List<Node> ret = new ArrayList<>();
List<? extends ConfigObject> list = config.getObjectList("peer.active");
for (ConfigObject configObject : list) {
Node n;
if (configObject.get("url") != null) {
String url = configObject.toConfig().getString("url");
n = new Node(url.startsWith("enode://") ? url : "enode://" + url);
} else if (configObject.get("ip") != null) {
String ip = configObject.toConfig().getString("ip");
int port = configObject.toConfig().getInt("port");
byte[] nodeId;
if (configObject.toConfig().hasPath("nodeId")) {
nodeId = Hex.decode(configObject.toConfig().getString("nodeId").trim());
if (nodeId.length != 64) {
throw new RuntimeException("Invalid config nodeId '" + nodeId + "' at " + configObject);
}
} else {
if (configObject.toConfig().hasPath("nodeName")) {
String nodeName = configObject.toConfig().getString("nodeName").trim();
// FIXME should be keccak-512 here ?
nodeId = ECKey.fromPrivate(sha3(nodeName.getBytes())).getNodeId();
} else {
throw new RuntimeException("Either nodeId or nodeName should be specified: " + configObject);
}
}
n = new Node(nodeId, ip, port);
} else {
throw new RuntimeException("Unexpected element within 'peer.active' config list: " + configObject);
}
ret.add(n);
}
return ret;
}
@ValidateMe
public NodeFilter peerTrusted() {
List<? extends ConfigObject> list = config.getObjectList("peer.trusted");
NodeFilter ret = new NodeFilter();
for (ConfigObject configObject : list) {
byte[] nodeId = null;
String ipMask = null;
if (configObject.get("nodeId") != null) {
nodeId = Hex.decode(configObject.toConfig().getString("nodeId").trim());
}
if (configObject.get("ip") != null) {
ipMask = configObject.toConfig().getString("ip").trim();
}
ret.add(nodeId, ipMask);
}
return ret;
}
@ValidateMe
public Integer blockQueueSize() {
return config.getInt("cache.blockQueueSize") * 1024 * 1024;
}
@ValidateMe
public Integer headerQueueSize() {
return config.getInt("cache.headerQueueSize") * 1024 * 1024;
}
@ValidateMe
public Integer peerChannelReadTimeout() {
return config.getInt("peer.channel.read.timeout");
}
@ValidateMe
public Integer traceStartBlock() {
return config.getInt("trace.startblock");
}
@ValidateMe
public boolean recordBlocks() {
return config.getBoolean("record.blocks");
}
@ValidateMe
public boolean dumpFull() {
return config.getBoolean("dump.full");
}
@ValidateMe
public String dumpDir() {
return config.getString("dump.dir");
}
@ValidateMe
public String dumpStyle() {
return config.getString("dump.style");
}
@ValidateMe
public int dumpBlock() {
return config.getInt("dump.block");
}
@ValidateMe
public String databaseDir() {
return databaseDir == null ? config.getString("database.dir") : databaseDir;
}
public String ethashDir() {
return config.hasPath("ethash.dir") ? config.getString("ethash.dir") : databaseDir();
}
public void setDataBaseDir(String dataBaseDir) {
this.databaseDir = dataBaseDir;
}
@ValidateMe
public boolean dumpCleanOnRestart() {
return config.getBoolean("dump.clean.on.restart");
}
@ValidateMe
public boolean playVM() {
return config.getBoolean("play.vm");
}
@ValidateMe
public boolean blockChainOnly() {
return config.getBoolean("blockchain.only");
}
@ValidateMe
public int syncPeerCount() {
return config.getInt("sync.peer.count");
}
public Integer syncVersion() {
if (!config.hasPath("sync.version")) {
return null;
}
return config.getInt("sync.version");
}
@ValidateMe
public boolean exitOnBlockConflict() {
return config.getBoolean("sync.exitOnBlockConflict");
}
@ValidateMe
public String projectVersion() {
return projectVersion;
}
@ValidateMe
public Integer databaseVersion() {
return databaseVersion;
}
@ValidateMe
public String projectVersionModifier() {
return projectVersionModifier;
}
@ValidateMe
public String helloPhrase() {
return config.getString("hello.phrase");
}
@ValidateMe
public String rootHashStart() {
return config.hasPath("root.hash.start") ? config.getString("root.hash.start") : null;
}
@ValidateMe
public List<String> peerCapabilities() {
return config.getStringList("peer.capabilities");
}
@ValidateMe
public boolean vmTrace() {
return vmTrace == null ? (vmTrace = config.getBoolean("vm.structured.trace")) : vmTrace;
}
@ValidateMe
public boolean vmTraceCompressed() {
return config.getBoolean("vm.structured.compressed");
}
@ValidateMe
public int vmTraceInitStorageLimit() {
return config.getInt("vm.structured.initStorageLimit");
}
@ValidateMe
public int cacheFlushBlocks() {
return config.getInt("cache.flush.blocks");
}
@ValidateMe
public String vmTraceDir() {
return config.getString("vm.structured.dir");
}
public String customSolcPath() {
return config.hasPath("solc.path") ? config.getString("solc.path"): null;
}
public String privateKey() {
if (config.hasPath("peer.privateKey")) {
String key = config.getString("peer.privateKey");
if (key.length() != 64 || !Utils.isHexEncoded(key)) {
throw new RuntimeException("The peer.privateKey needs to be Hex encoded and 32 byte length");
}
return key;
} else {
return getGeneratedNodePrivateKey();
}
}
private String getGeneratedNodePrivateKey() {
if (generatedNodePrivateKey == null) {
generatedNodePrivateKey = generateNodeIdStrategy.getNodePrivateKey();
}
return generatedNodePrivateKey;
}
public ECKey getMyKey() {
return ECKey.fromPrivate(Hex.decode(privateKey()));
}
/**
* Home NodeID calculated from 'peer.privateKey' property
*/
public byte[] nodeId() {
return getMyKey().getNodeId();
}
@ValidateMe
public int networkId() {
return config.getInt("peer.networkId");
}
@ValidateMe
public int maxActivePeers() {
return config.getInt("peer.maxActivePeers");
}
@ValidateMe
public boolean eip8() {
return config.getBoolean("peer.p2p.eip8");
}
@ValidateMe
public int listenPort() {
return config.getInt("peer.listen.port");
}
/**
* This can be a blocking call with long timeout (thus no ValidateMe)
*/
public String bindIp() {
if (!config.hasPath("peer.discovery.bind.ip") || config.getString("peer.discovery.bind.ip").trim().isEmpty()) {
if (bindIp == null) {
logger.info("Bind address wasn't set, Punching to identify it...");
try (Socket s = new Socket("www.google.com", 80)) {
bindIp = s.getLocalAddress().getHostAddress();
logger.info("UDP local bound to: {}", bindIp);
} catch (IOException e) {
logger.warn("Can't get bind IP. Fall back to 0.0.0.0: " + e);
bindIp = "0.0.0.0";
}
}
return bindIp;
} else {
return config.getString("peer.discovery.bind.ip").trim();
}
}
/**
* This can be a blocking call with long timeout (thus no ValidateMe)
*/
public String externalIp() {
if (!config.hasPath("peer.discovery.external.ip") || config.getString("peer.discovery.external.ip").trim().isEmpty()) {
if (externalIp == null) {
logger.info("External IP wasn't set, using checkip.amazonaws.com to identify it...");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
new URL("http://checkip.amazonaws.com").openStream()));
externalIp = in.readLine();
if (externalIp == null || externalIp.trim().isEmpty()) {
throw new IOException("Invalid address: '" + externalIp + "'");
}
try {
InetAddress.getByName(externalIp);
} catch (Exception e) {
throw new IOException("Invalid address: '" + externalIp + "'");
}
logger.info("External address identified: {}", externalIp);
} catch (IOException e) {
externalIp = bindIp();
logger.warn("Can't get external IP. Fall back to peer.bind.ip: " + externalIp + " :" + e);
}
}
return externalIp;
} else {
return config.getString("peer.discovery.external.ip").trim();
}
}
@ValidateMe
public String getKeyValueDataSource() {
return config.getString("keyvalue.datasource");
}
@ValidateMe
public boolean isSyncEnabled() {
return this.syncEnabled == null ? config.getBoolean("sync.enabled") : syncEnabled;
}
public void setSyncEnabled(Boolean syncEnabled) {
this.syncEnabled = syncEnabled;
}
@ValidateMe
public boolean isFastSyncEnabled() {
return isSyncEnabled() && config.getBoolean("sync.fast.enabled");
}
@ValidateMe
public byte[] getFastSyncPivotBlockHash() {
if (!config.hasPath("sync.fast.pivotBlockHash")) return null;
byte[] ret = Hex.decode(config.getString("sync.fast.pivotBlockHash"));
if (ret.length != 32) throw new RuntimeException("Invalid block hash length: " + toHexString(ret));
return ret;
}
@ValidateMe
public boolean fastSyncBackupState() {
return config.getBoolean("sync.fast.backupState");
}
@ValidateMe
public boolean fastSyncSkipHistory() {
return config.getBoolean("sync.fast.skipHistory");
}
@ValidateMe
public int makeDoneByTimeout() {
return config.getInt("sync.makeDoneByTimeout");
}
@ValidateMe
public boolean isPublicHomeNode() { return config.getBoolean("peer.discovery.public.home.node");}
@ValidateMe
public String genesisInfo() {
return genesisInfo == null ? config.getString("genesis") : genesisInfo;
}
@ValidateMe
public int txOutdatedThreshold() {
return config.getInt("transaction.outdated.threshold");
}
public void setGenesisInfo(String genesisInfo){
this.genesisInfo = genesisInfo;
}
@ValidateMe
public boolean minerStart() {
return config.getBoolean("mine.start");
}
@ValidateMe
public byte[] getMinerCoinbase() {
String sc = config.getString("mine.coinbase");
byte[] c = ByteUtil.hexStringToBytes(sc);
if (c.length != 20) throw new RuntimeException("mine.coinbase has invalid value: '" + sc + "'");
return c;
}
@ValidateMe
public byte[] getMineExtraData() {
byte[] bytes;
if (config.hasPath("mine.extraDataHex")) {
bytes = Hex.decode(config.getString("mine.extraDataHex"));
} else {
bytes = config.getString("mine.extraData").getBytes();
}
if (bytes.length > 32) throw new RuntimeException("mine.extraData exceed 32 bytes length: " + bytes.length);
return bytes;
}
@ValidateMe
public BigInteger getMineMinGasPrice() {
return new BigInteger(config.getString("mine.minGasPrice"));
}
@ValidateMe
public long getMineMinBlockTimeoutMsec() {
return config.getLong("mine.minBlockTimeoutMsec");
}
@ValidateMe
public int getMineCpuThreads() {
return config.getInt("mine.cpuMineThreads");
}
@ValidateMe
public boolean isMineFullDataset() {
return config.getBoolean("mine.fullDataSet");
}
@ValidateMe
public String getCryptoProviderName() {
return config.getString("crypto.providerName");
}
@ValidateMe
public boolean recordInternalTransactionsData() {
if (recordInternalTransactionsData == null) {
recordInternalTransactionsData = config.getBoolean("record.internal.transactions.data");
}
return recordInternalTransactionsData;
}
public void setRecordInternalTransactionsData(Boolean recordInternalTransactionsData) {
this.recordInternalTransactionsData = recordInternalTransactionsData;
}
@ValidateMe
public String getHash256AlgName() {
return config.getString("crypto.hash.alg256");
}
@ValidateMe
public String getHash512AlgName() {
return config.getString("crypto.hash.alg512");
}
@ValidateMe
public String getEthashMode() {
return config.getString("sync.ethash");
}
private GenesisJson getGenesisJson() {
if (genesisJson == null) {
genesisJson = GenesisLoader.loadGenesisJson(this, classLoader);
}
return genesisJson;
}
public Genesis getGenesis() {
if (genesis == null) {
genesis = GenesisLoader.parseGenesis(getBlockchainConfig(), getGenesisJson());
}
return genesis;
}
/**
* Method used in StandaloneBlockchain.
*/
public Genesis useGenesis(InputStream inputStream) {
genesisJson = GenesisLoader.loadGenesisJson(inputStream);
genesis = GenesisLoader.parseGenesis(getBlockchainConfig(), getGenesisJson());
return genesis;
}
public String dump() {
return config.root().render(ConfigRenderOptions.defaults().setComments(false));
}
/*
*
* Testing
*
*/
public boolean vmTestLoadLocal() {
return config.hasPath("GitHubTests.VMTest.loadLocal") ?
config.getBoolean("GitHubTests.VMTest.loadLocal") : DEFAULT_VMTEST_LOAD_LOCAL;
}
public String blocksLoader() {
return config.hasPath("blocks.loader") ?
config.getString("blocks.loader") : DEFAULT_BLOCKS_LOADER;
}
public String githubTestsPath() {
return config.hasPath("GitHubTests.testPath") ?
config.getString("GitHubTests.testPath") : "";
}
public boolean githubTestsLoadLocal() {
return config.hasPath("GitHubTests.testPath") &&
!config.getString("GitHubTests.testPath").isEmpty();
}
void setGenerateNodeIdStrategy(GenerateNodeIdStrategy generateNodeIdStrategy) {
this.generateNodeIdStrategy = generateNodeIdStrategy;
}
}
| 35,655
| 35.016162
| 204
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/config/GetNodeIdFromPropsFile.java
|
/*
* Copyright (c) [2017] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.config;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Properties;
/**
* Strategy to generate the nodeId and the nodePrivateKey from a nodeId.properties file.
* <p>
* If the nodeId.properties file doesn't exist, it uses the
* {@link GetNodeIdFromPropsFile#fallbackGenerateNodeIdStrategy} as a fallback strategy
* to generate the nodeId and nodePrivateKey.
*
* @author Lucas Saldanha
* @since 14.12.2017
*/
public class GetNodeIdFromPropsFile implements GenerateNodeIdStrategy {
private String databaseDir;
private GenerateNodeIdStrategy fallbackGenerateNodeIdStrategy;
GetNodeIdFromPropsFile(String databaseDir) {
this.databaseDir = databaseDir;
}
@Override
public String getNodePrivateKey() {
Properties props = new Properties();
File file = new File(databaseDir, "nodeId.properties");
if (file.canRead()) {
try (Reader r = new FileReader(file)) {
props.load(r);
return props.getProperty("nodeIdPrivateKey");
} catch (IOException e) {
throw new RuntimeException("Error reading 'nodeId.properties' file", e);
}
} else {
if (fallbackGenerateNodeIdStrategy != null) {
return fallbackGenerateNodeIdStrategy.getNodePrivateKey();
} else {
throw new RuntimeException("Can't read 'nodeId.properties' and no fallback method has been set");
}
}
}
public GenerateNodeIdStrategy withFallback(GenerateNodeIdStrategy generateNodeIdStrategy) {
this.fallbackGenerateNodeIdStrategy = generateNodeIdStrategy;
return this;
}
}
| 2,550
| 35.442857
| 113
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/config/NodeFilter.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.config;
import org.ethereum.net.rlpx.Node;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by Anton Nashatyrev on 14.01.2016.
*/
public class NodeFilter {
private List<Entry> entries = new ArrayList<>();
public void add(byte[] nodeId, String hostIpPattern) {
entries.add(new Entry(nodeId, hostIpPattern));
}
public boolean accept(Node node) {
for (Entry entry : entries) {
if (entry.accept(node)) return true;
}
return false;
}
public boolean accept(InetAddress nodeAddr) {
for (Entry entry : entries) {
if (entry.accept(nodeAddr)) return true;
}
return false;
}
private class Entry {
byte[] nodeId;
String hostIpPattern;
public Entry(byte[] nodeId, String hostIpPattern) {
this.nodeId = nodeId;
if (hostIpPattern != null) {
int idx = hostIpPattern.indexOf("*");
if (idx > 0) {
hostIpPattern = hostIpPattern.substring(0, idx);
}
}
this.hostIpPattern = hostIpPattern;
}
public boolean accept(InetAddress nodeAddr) {
if (hostIpPattern == null) return true;
String ip = nodeAddr.getHostAddress();
return hostIpPattern != null && ip.startsWith(hostIpPattern);
}
public boolean accept(Node node) {
try {
boolean shouldAcceptNodeId = nodeId == null || Arrays.equals(node.getId(), nodeId);
if (!shouldAcceptNodeId) {
return false;
}
InetAddress nodeAddress = InetAddress.getByName(node.getHost());
return (hostIpPattern == null || accept(nodeAddress));
} catch (UnknownHostException e) {
return false;
}
}
}
}
| 2,819
| 31.413793
| 99
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/config/GenerateNodeIdStrategy.java
|
/*
* Copyright (c) [2017] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.config;
/**
* Strategy interface to generate the nodeId and the nodePrivateKey.
* <p>
* Two strategies are available:
* <ul>
* <li>{@link GetNodeIdFromPropsFile}: searches for a nodeId.properties
* and uses the values in the file to set the nodeId and the nodePrivateKey.</li>
* <li>{@link GenerateNodeIdRandomly}: generates a nodeId.properties file
* with a generated nodeId and nodePrivateKey.</li>
* </ul>
*
* @author Lucas Saldanha
* @see SystemProperties#getGeneratedNodePrivateKey()
* @since 14.12.2017
*/
public interface GenerateNodeIdStrategy {
String getNodePrivateKey();
}
| 1,416
| 34.425
| 81
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/config/BlockchainNetConfig.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.config;
import org.ethereum.core.BlockHeader;
/**
* Describes a set of configs for a specific blockchain depending on the block number
* E.g. the main Ethereum net has at least FrontierConfig and HomesteadConfig depending on the block
*
* Created by Anton Nashatyrev on 25.02.2016.
*/
public interface BlockchainNetConfig {
/**
* Get the config for the specific block
*/
BlockchainConfig getConfigForBlock(long blockNumber);
/**
* Returns the constants common for all the blocks in this blockchain
*/
Constants getCommonConstants();
}
| 1,391
| 33.8
| 100
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/config/GenerateNodeIdRandomly.java
|
/*
* Copyright (c) [2017] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.config;
import org.ethereum.crypto.ECKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Properties;
/**
* Strategy to randomly generate the nodeId and the nodePrivateKey.
*
* @author Lucas Saldanha
* @since 14.12.2017
*/
public class GenerateNodeIdRandomly implements GenerateNodeIdStrategy {
private static Logger logger = LoggerFactory.getLogger("general");
private String databaseDir;
GenerateNodeIdRandomly(String databaseDir) {
this.databaseDir = databaseDir;
}
@Override
public String getNodePrivateKey() {
ECKey key = new ECKey();
Properties props = new Properties();
props.setProperty("nodeIdPrivateKey", Hex.toHexString(key.getPrivKeyBytes()));
props.setProperty("nodeId", Hex.toHexString(key.getNodeId()));
File file = new File(databaseDir, "nodeId.properties");
file.getParentFile().mkdirs();
try (Writer writer = new FileWriter(file)) {
props.store(writer, "Generated NodeID. To use your own nodeId please refer to 'peer.privateKey' config option.");
} catch (IOException e) {
throw new RuntimeException(e);
}
logger.info("New nodeID generated: " + props.getProperty("nodeId"));
logger.info("Generated nodeID and its private key stored in " + file);
return props.getProperty("nodeIdPrivateKey");
}
}
| 2,364
| 33.779412
| 125
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/config/blockchain/AbstractDaoConfig.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.config.blockchain;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.ethereum.config.BlockchainConfig;
import org.ethereum.core.BlockHeader;
import org.ethereum.core.Transaction;
import org.ethereum.validator.BlockHeaderRule;
import org.ethereum.validator.BlockHeaderValidator;
import org.ethereum.validator.ExtraDataPresenceRule;
import org.spongycastle.util.encoders.Hex;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;
/**
* Created by Stan Reshetnyk on 26.12.16.
*/
public abstract class AbstractDaoConfig extends FrontierConfig {
/**
* Hardcoded values from live network
*/
public static final long ETH_FORK_BLOCK_NUMBER = 1_920_000;
// "dao-hard-fork" encoded message
public static final byte[] DAO_EXTRA_DATA = Hex.decode("64616f2d686172642d666f726b");
private final long EXTRA_DATA_AFFECTS_BLOCKS_NUMBER = 10;
// MAYBE find a way to remove block number value from blockchain config
protected long forkBlockNumber;
// set in child classes
protected boolean supportFork;
private BlockchainConfig parent;
protected void initDaoConfig(BlockchainConfig parent, long forkBlockNumber) {
this.parent = parent;
this.constants = parent.getConstants();
this.forkBlockNumber = forkBlockNumber;
BlockHeaderRule rule = new ExtraDataPresenceRule(DAO_EXTRA_DATA, supportFork);
headerValidators().add(Pair.of(forkBlockNumber, new BlockHeaderValidator(rule)));
}
/**
* Miners should include marker for initial 10 blocks. Either "dao-hard-fork" or ""
*/
@Override
public byte[] getExtraData(byte[] minerExtraData, long blockNumber) {
if (blockNumber >= forkBlockNumber && blockNumber < forkBlockNumber + EXTRA_DATA_AFFECTS_BLOCKS_NUMBER ) {
if (supportFork) {
return DAO_EXTRA_DATA;
} else {
return new byte[0];
}
}
return minerExtraData;
}
@Override
public BigInteger calcDifficulty(BlockHeader curBlock, BlockHeader parent) {
return this.parent.calcDifficulty(curBlock, parent);
}
@Override
public long getTransactionCost(Transaction tx) {
return parent.getTransactionCost(tx);
}
@Override
public boolean acceptTransactionSignature(Transaction tx) {
return parent.acceptTransactionSignature(tx);
}
}
| 3,272
| 33.452632
| 114
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/config/blockchain/PetersburgConfig.java
|
package org.ethereum.config.blockchain;
import org.ethereum.config.BlockchainConfig;
/**
* A version of Constantinople Hard Fork after removing eip-1283.
* <p>
* Unofficial name 'Petersburg', includes:
* <ul>
* <li>1234 - Constantinople Difficulty Bomb Delay and Block Reward Adjustment (2 ETH)</li>
* <li>145 - Bitwise shifting instructions in EVM</li>
* <li>1014 - Skinny CREATE2</li>
* <li>1052 - EXTCODEHASH opcode</li>
* </ul>
*/
public class PetersburgConfig extends ConstantinopleConfig {
public PetersburgConfig(BlockchainConfig parent) {
super(parent);
}
@Override
public boolean eip1283() {
return false;
}
}
| 670
| 23.851852
| 95
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/config/blockchain/ConstantinopleConfig.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.config.blockchain;
import org.ethereum.config.BlockchainConfig;
import org.ethereum.config.Constants;
import org.ethereum.config.ConstantsAdapter;
import org.ethereum.core.BlockHeader;
import org.ethereum.util.blockchain.EtherUtil;
import java.math.BigInteger;
/**
* EIPs included in the Constantinople Hard Fork:
* <ul>
* <li>1234 - Constantinople Difficulty Bomb Delay and Block Reward Adjustment (2 ETH)</li>
* <li>145 - Bitwise shifting instructions in EVM</li>
* <li>1014 - Skinny CREATE2</li>
* <li>1052 - EXTCODEHASH opcode</li>
* <li>1283 - Net gas metering for SSTORE without dirty maps</li>
* </ul>
*/
public class ConstantinopleConfig extends ByzantiumConfig {
private final Constants constants;
public ConstantinopleConfig(BlockchainConfig parent) {
super(parent);
constants = new ConstantsAdapter(super.getConstants()) {
private final BigInteger BLOCK_REWARD = EtherUtil.convert(2, EtherUtil.Unit.ETHER);
@Override
public BigInteger getBLOCK_REWARD() {
return BLOCK_REWARD;
}
};
}
@Override
public Constants getConstants() {
return constants;
}
@Override
protected int getExplosion(BlockHeader curBlock, BlockHeader parent) {
int periodCount = (int) (Math.max(0, curBlock.getNumber() - 5_000_000) / getConstants().getEXP_DIFFICULTY_PERIOD());
return periodCount - 2;
}
@Override
public boolean eip1052() {
return true;
}
@Override
public boolean eip145() {
return true;
}
@Override
public boolean eip1283() {
return true;
}
@Override
public boolean eip1014() {
return true;
}
}
| 2,572
| 29.270588
| 124
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/config/blockchain/FrontierConfig.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.config.blockchain;
import org.ethereum.config.Constants;
import org.ethereum.core.Transaction;
import org.ethereum.util.blockchain.EtherUtil;
import java.math.BigInteger;
/**
* Created by Anton Nashatyrev on 25.02.2016.
*/
public class FrontierConfig extends OlympicConfig {
public static class FrontierConstants extends Constants {
private static final BigInteger BLOCK_REWARD = EtherUtil.convert(5, EtherUtil.Unit.ETHER);
@Override
public int getDURATION_LIMIT() {
return 13;
}
@Override
public BigInteger getBLOCK_REWARD() {
return BLOCK_REWARD;
}
@Override
public int getMIN_GAS_LIMIT() {
return 5000;
}
};
public FrontierConfig() {
this(new FrontierConstants());
}
public FrontierConfig(Constants constants) {
super(constants);
}
@Override
public boolean acceptTransactionSignature(Transaction tx) {
if (!super.acceptTransactionSignature(tx)) return false;
if (tx.getSignature() == null) return false;
return tx.getSignature().validateComponents();
}
}
| 1,975
| 28.492537
| 98
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/config/blockchain/RopstenConfig.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.config.blockchain;
import org.apache.commons.lang3.tuple.Pair;
import org.ethereum.config.BlockchainConfig;
import org.ethereum.validator.BlockCustomHashRule;
import org.ethereum.validator.BlockHeaderRule;
import org.ethereum.validator.BlockHeaderValidator;
import org.spongycastle.util.encoders.Hex;
import java.util.Arrays;
import java.util.List;
/**
* Created by Anton Nashatyrev on 21.11.2016.
*/
public class RopstenConfig extends Eip160HFConfig {
// Check for 1 known block to exclude fake peers
private static final long CHECK_BLOCK_NUMBER = 10;
private static final byte[] CHECK_BLOCK_HASH = Hex.decode("b3074f936815a0425e674890d7db7b5e94f3a06dca5b22d291b55dcd02dde93e");
public RopstenConfig(BlockchainConfig parent) {
super(parent);
headerValidators().add(Pair.of(CHECK_BLOCK_NUMBER, new BlockHeaderValidator(new BlockCustomHashRule(CHECK_BLOCK_HASH))));
}
@Override
public Integer getChainId() {
return 3;
}
}
| 1,796
| 35.673469
| 130
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/config/blockchain/Eip160HFConfig.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.config.blockchain;
import org.ethereum.config.BlockchainConfig;
import org.ethereum.config.Constants;
import org.ethereum.config.ConstantsAdapter;
import org.ethereum.core.Transaction;
import org.ethereum.vm.GasCost;
import java.util.Objects;
import static org.ethereum.config.blockchain.HomesteadConfig.SECP256K1N_HALF;
/**
* Hard fork includes following EIPs:
* EIP 155 - Simple replay attack protection
* EIP 160 - EXP cost increase
* EIP 161 - State trie clearing (invariant-preserving alternative)
*/
public class Eip160HFConfig extends Eip150HFConfig {
static class GasCostEip160HF extends GasCostEip150HF {
public int getEXP_BYTE_GAS() { return 50; }
}
private static final GasCost NEW_GAS_COST = new GasCostEip160HF();
private final Constants constants;
public Eip160HFConfig(BlockchainConfig parent) {
super(parent);
constants = new ConstantsAdapter(parent.getConstants()) {
@Override
public int getMAX_CONTRACT_SZIE() {
return 0x6000;
}
};
}
@Override
public GasCost getGasCost() {
return NEW_GAS_COST;
}
@Override
public boolean eip161() {
return true;
}
@Override
public Integer getChainId() {
return 1;
}
@Override
public Constants getConstants() {
return constants;
}
@Override
public boolean acceptTransactionSignature(Transaction tx) {
if (tx.getSignature() == null) return false;
// Restoring old logic. Making this through inheritance stinks too much
if (!tx.getSignature().validateComponents() ||
tx.getSignature().s.compareTo(SECP256K1N_HALF) > 0) return false;
return tx.getChainId() == null || Objects.equals(getChainId(), tx.getChainId());
}
}
| 2,662
| 29.609195
| 89
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/config/blockchain/MordenConfig.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.config.blockchain;
import java.math.BigInteger;
/**
* Created by Anton Nashatyrev on 25.02.2016.
*/
public class MordenConfig {
private static final BigInteger NONSE = BigInteger.valueOf(0x100000);
public static class Frontier extends FrontierConfig {
public Frontier() {
super(new FrontierConstants() {
@Override
public BigInteger getInitialNonce() {
return NONSE;
}
});
}
}
public static class Homestead extends HomesteadConfig {
public Homestead() {
super(new HomesteadConstants() {
@Override
public BigInteger getInitialNonce() {
return NONSE;
}
});
}
}
}
| 1,613
| 31.28
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/config/blockchain/AbstractConfig.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.config.blockchain;
import org.apache.commons.lang3.tuple.Pair;
import org.ethereum.config.BlockchainConfig;
import org.ethereum.config.BlockchainNetConfig;
import org.ethereum.config.Constants;
import org.ethereum.config.SystemProperties;
import org.ethereum.core.*;
import org.ethereum.db.BlockStore;
import org.ethereum.mine.EthashMiner;
import org.ethereum.mine.MinerIfc;
import org.ethereum.validator.BlockHeaderValidator;
import org.ethereum.vm.DataWord;
import org.ethereum.vm.GasCost;
import org.ethereum.vm.OpCode;
import org.ethereum.vm.program.Program;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import static org.ethereum.util.BIUtil.max;
/**
* BlockchainForkConfig is also implemented by this class - its (mostly testing) purpose to represent
* the specific config for all blocks on the chain (kinda constant config).
*
* Created by Anton Nashatyrev on 25.02.2016.
*/
public abstract class AbstractConfig implements BlockchainConfig, BlockchainNetConfig {
private static final GasCost GAS_COST = new GasCost();
protected Constants constants;
protected MinerIfc miner;
private List<Pair<Long, BlockHeaderValidator>> headerValidators = new ArrayList<>();
public AbstractConfig() {
this(new Constants());
}
public AbstractConfig(Constants constants) {
this.constants = constants;
}
@Override
public Constants getConstants() {
return constants;
}
@Override
public BlockchainConfig getConfigForBlock(long blockHeader) {
return this;
}
@Override
public Constants getCommonConstants() {
return getConstants();
}
@Override
public MinerIfc getMineAlgorithm(SystemProperties config) {
if (miner == null) miner = new EthashMiner(config);
return miner;
}
@Override
public BigInteger calcDifficulty(BlockHeader curBlock, BlockHeader parent) {
BigInteger pd = parent.getDifficultyBI();
BigInteger quotient = pd.divide(getConstants().getDIFFICULTY_BOUND_DIVISOR());
BigInteger sign = getCalcDifficultyMultiplier(curBlock, parent);
BigInteger fromParent = pd.add(quotient.multiply(sign));
BigInteger difficulty = max(getConstants().getMINIMUM_DIFFICULTY(), fromParent);
int explosion = getExplosion(curBlock, parent);
if (explosion >= 0) {
difficulty = max(getConstants().getMINIMUM_DIFFICULTY(), difficulty.add(BigInteger.ONE.shiftLeft(explosion)));
}
return difficulty;
}
protected int getExplosion(BlockHeader curBlock, BlockHeader parent) {
int periodCount = (int) (curBlock.getNumber() / getConstants().getEXP_DIFFICULTY_PERIOD());
return periodCount - 2;
}
@Override
public boolean acceptTransactionSignature(Transaction tx) {
return Objects.equals(tx.getChainId(), getChainId());
}
@Override
public String validateTransactionChanges(BlockStore blockStore, Block curBlock, Transaction tx,
Repository repository) {
return null;
}
@Override
public void hardForkTransfers(Block block, Repository repo) {}
@Override
public byte[] getExtraData(byte[] minerExtraData, long blockNumber) {
return minerExtraData;
}
@Override
public List<Pair<Long, BlockHeaderValidator>> headerValidators() {
return headerValidators;
}
@Override
public GasCost getGasCost() {
return GAS_COST;
}
@Override
public DataWord getCallGas(OpCode op, DataWord requestedGas, DataWord availableGas) throws Program.OutOfGasException {
if (requestedGas.compareTo(availableGas) > 0) {
throw Program.Exception.notEnoughOpGas(op, requestedGas, availableGas);
}
return requestedGas;
}
@Override
public DataWord getCreateGas(DataWord availableGas) {
return availableGas;
}
@Override
public boolean eip161() {
return false;
}
@Override
public Integer getChainId() {
return null;
}
@Override
public boolean eip198() {
return false;
}
@Override
public boolean eip206() {
return false;
}
@Override
public boolean eip211() {
return false;
}
@Override
public boolean eip212() {
return false;
}
@Override
public boolean eip213() {
return false;
}
@Override
public boolean eip214() {
return false;
}
@Override
public boolean eip658() {
return false;
}
@Override
public boolean eip1052() {
return false;
}
@Override
public boolean eip145() {
return false;
}
@Override
public boolean eip1283() {
return false;
}
@Override
public boolean eip1014() {
return false;
}
@Override
public String toString() {
return getClass().getSimpleName();
}
}
| 5,871
| 25.45045
| 122
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/config/blockchain/ByzantiumConfig.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.config.blockchain;
import org.ethereum.config.BlockchainConfig;
import org.ethereum.config.Constants;
import org.ethereum.config.ConstantsAdapter;
import org.ethereum.core.BlockHeader;
import org.ethereum.util.blockchain.EtherUtil;
import java.math.BigInteger;
import static org.ethereum.util.BIUtil.max;
/**
* EIPs included in the Hard Fork:
* <ul>
* <li>100 - Change difficulty adjustment to target mean block time including uncles</li>
* <li>140 - REVERT instruction in the Ethereum Virtual Machine</li>
* <li>196 - Precompiled contracts for addition and scalar multiplication on the elliptic curve alt_bn128</li>
* <li>197 - Precompiled contracts for optimal Ate pairing check on the elliptic curve alt_bn128</li>
* <li>198 - Precompiled contract for bigint modular exponentiation</li>
* <li>211 - New opcodes: RETURNDATASIZE and RETURNDATACOPY</li>
* <li>214 - New opcode STATICCALL</li>
* <li>658 - Embedding transaction return data in receipts</li>
* </ul>
*
* @author Mikhail Kalinin
* @since 14.08.2017
*/
public class ByzantiumConfig extends Eip160HFConfig {
private final Constants constants;
public ByzantiumConfig(BlockchainConfig parent) {
super(parent);
constants = new ConstantsAdapter(super.getConstants()) {
private final BigInteger BLOCK_REWARD = EtherUtil.convert(3, EtherUtil.Unit.ETHER);
@Override
public BigInteger getBLOCK_REWARD() {
return BLOCK_REWARD;
}
};
}
@Override
public Constants getConstants() {
return constants;
}
@Override
public BigInteger calcDifficulty(BlockHeader curBlock, BlockHeader parent) {
BigInteger pd = parent.getDifficultyBI();
BigInteger quotient = pd.divide(getConstants().getDIFFICULTY_BOUND_DIVISOR());
BigInteger sign = getCalcDifficultyMultiplier(curBlock, parent);
BigInteger fromParent = pd.add(quotient.multiply(sign));
BigInteger difficulty = max(getConstants().getMINIMUM_DIFFICULTY(), fromParent);
int explosion = getExplosion(curBlock, parent);
if (explosion >= 0) {
difficulty = max(getConstants().getMINIMUM_DIFFICULTY(), difficulty.add(BigInteger.ONE.shiftLeft(explosion)));
}
return difficulty;
}
protected int getExplosion(BlockHeader curBlock, BlockHeader parent) {
int periodCount = (int) (Math.max(0, curBlock.getNumber() - 3_000_000) / getConstants().getEXP_DIFFICULTY_PERIOD());
return periodCount - 2;
}
@Override
public BigInteger getCalcDifficultyMultiplier(BlockHeader curBlock, BlockHeader parent) {
long unclesAdj = parent.hasUncles() ? 2 : 1;
return BigInteger.valueOf(Math.max(unclesAdj - (curBlock.getTimestamp() - parent.getTimestamp()) / 9, -99));
}
@Override
public boolean eip198() {
return true;
}
@Override
public boolean eip206() {
return true;
}
@Override
public boolean eip211() {
return true;
}
@Override
public boolean eip212() {
return true;
}
@Override
public boolean eip213() {
return true;
}
@Override
public boolean eip214() {
return true;
}
@Override
public boolean eip658() {
return true;
}
}
| 4,183
| 30.69697
| 124
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/config/blockchain/OlympicConfig.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.config.blockchain;
import org.apache.commons.lang3.ArrayUtils;
import org.ethereum.config.Constants;
import org.ethereum.core.BlockHeader;
import org.ethereum.core.Transaction;
import java.math.BigInteger;
/**
* Created by Anton Nashatyrev on 25.02.2016.
*/
public class OlympicConfig extends AbstractConfig {
public OlympicConfig() {
}
public OlympicConfig(Constants constants) {
super(constants);
}
@Override
public BigInteger getCalcDifficultyMultiplier(BlockHeader curBlock, BlockHeader parent) {
return BigInteger.valueOf(curBlock.getTimestamp() >= parent.getTimestamp() +
getConstants().getDURATION_LIMIT() ? -1 : 1);
}
@Override
public long getTransactionCost(Transaction tx) {
long nonZeroes = tx.nonZeroDataBytes();
long zeroVals = ArrayUtils.getLength(tx.getData()) - nonZeroes;
return getGasCost().getTRANSACTION() + zeroVals * getGasCost().getTX_ZERO_DATA() +
nonZeroes * getGasCost().getTX_NO_ZERO_DATA();
}
}
| 1,857
| 33.407407
| 93
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/config/blockchain/HomesteadConfig.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.config.blockchain;
import org.apache.commons.lang3.ArrayUtils;
import org.ethereum.config.Constants;
import org.ethereum.core.BlockHeader;
import org.ethereum.core.Transaction;
import java.math.BigInteger;
/**
* Created by Anton Nashatyrev on 25.02.2016.
*/
public class HomesteadConfig extends FrontierConfig {
static final BigInteger SECP256K1N_HALF = Constants.getSECP256K1N().divide(BigInteger.valueOf(2));
public static class HomesteadConstants extends FrontierConstants {
@Override
public boolean createEmptyContractOnOOG() {
return false;
}
@Override
public boolean hasDelegateCallOpcode() {
return true;
}
};
public HomesteadConfig() {
this(new HomesteadConstants());
}
public HomesteadConfig(Constants constants) {
super(constants);
}
@Override
public BigInteger getCalcDifficultyMultiplier(BlockHeader curBlock, BlockHeader parent) {
return BigInteger.valueOf(Math.max(1 - (curBlock.getTimestamp() - parent.getTimestamp()) / 10, -99));
}
@Override
public long getTransactionCost(Transaction tx) {
long nonZeroes = tx.nonZeroDataBytes();
long zeroVals = ArrayUtils.getLength(tx.getData()) - nonZeroes;
return (tx.isContractCreation() ? getGasCost().getTRANSACTION_CREATE_CONTRACT() : getGasCost().getTRANSACTION())
+ zeroVals * getGasCost().getTX_ZERO_DATA() + nonZeroes * getGasCost().getTX_NO_ZERO_DATA();
}
@Override
public boolean acceptTransactionSignature(Transaction tx) {
if (!super.acceptTransactionSignature(tx)) return false;
if (tx.getSignature() == null) return false;
return tx.getSignature().s.compareTo(SECP256K1N_HALF) <= 0;
}
}
| 2,605
| 33.746667
| 120
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/config/blockchain/ETCFork3M.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.config.blockchain;
import org.ethereum.config.BlockchainConfig;
import org.ethereum.core.BlockHeader;
import java.math.BigInteger;
import static org.ethereum.util.BIUtil.max;
/**
* Ethereum Classic HF on Block #3_000_000:
* - EXP reprice (EIP-160)
* - Replay Protection (EIP-155) (chainID: 61)
* - Difficulty Bomb delay (ECIP-1010) (https://github.com/ethereumproject/ECIPs/blob/master/ECIPs/ECIP-1010.md)
*
* Created by Anton Nashatyrev on 13.01.2017.
*/
public class ETCFork3M extends Eip160HFConfig {
public ETCFork3M(BlockchainConfig parent) {
super(parent);
}
@Override
public Integer getChainId() {
return 61;
}
@Override
public boolean eip161() {
return false;
}
@Override
public BigInteger calcDifficulty(BlockHeader curBlock, BlockHeader parent) {
BigInteger pd = parent.getDifficultyBI();
BigInteger quotient = pd.divide(getConstants().getDIFFICULTY_BOUND_DIVISOR());
BigInteger sign = getCalcDifficultyMultiplier(curBlock, parent);
BigInteger fromParent = pd.add(quotient.multiply(sign));
BigInteger difficulty = max(getConstants().getMINIMUM_DIFFICULTY(), fromParent);
int explosion = getExplosion(curBlock, parent);
if (explosion >= 0) {
difficulty = max(getConstants().getMINIMUM_DIFFICULTY(), difficulty.add(BigInteger.ONE.shiftLeft(explosion)));
}
return difficulty;
}
@Override
public BigInteger getCalcDifficultyMultiplier(BlockHeader curBlock, BlockHeader parent) {
return BigInteger.valueOf(Math.max(1 - (curBlock.getTimestamp() - parent.getTimestamp()) / 10, -99));
}
protected int getExplosion(BlockHeader curBlock, BlockHeader parent) {
int pauseBlock = 3000000;
int contBlock = 5000000;
int delay = (contBlock - pauseBlock) / 100000;
int fixedDiff = (pauseBlock / 100000) - 2;
if (curBlock.getNumber() < contBlock) {
return fixedDiff;
} else {
return (int) ((curBlock.getNumber() / 100000) - delay - 2);
}
}
}
| 2,928
| 32.284091
| 122
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/config/blockchain/Eip150HFConfig.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.config.blockchain;
import org.apache.commons.lang3.tuple.Pair;
import org.ethereum.config.BlockchainConfig;
import org.ethereum.config.BlockchainNetConfig;
import org.ethereum.config.Constants;
import org.ethereum.config.SystemProperties;
import org.ethereum.core.Block;
import org.ethereum.core.BlockHeader;
import org.ethereum.core.Repository;
import org.ethereum.core.Transaction;
import org.ethereum.db.BlockStore;
import org.ethereum.mine.MinerIfc;
import org.ethereum.util.Utils;
import org.ethereum.validator.BlockHeaderValidator;
import org.ethereum.vm.DataWord;
import org.ethereum.vm.GasCost;
import org.ethereum.vm.OpCode;
import org.ethereum.vm.program.Program;
import java.math.BigInteger;
import java.util.List;
/**
* Created by Anton Nashatyrev on 14.10.2016.
*/
public class Eip150HFConfig implements BlockchainConfig, BlockchainNetConfig {
protected BlockchainConfig parent;
static class GasCostEip150HF extends GasCost {
public int getBALANCE() { return 400; }
public int getEXT_CODE_SIZE() { return 700; }
public int getEXT_CODE_COPY() { return 700; }
public int getSLOAD() { return 200; }
public int getCALL() { return 700; }
public int getSUICIDE() { return 5000; }
public int getNEW_ACCT_SUICIDE() { return 25000; }
};
private static final GasCost NEW_GAS_COST = new GasCostEip150HF();
public Eip150HFConfig(BlockchainConfig parent) {
this.parent = parent;
}
@Override
public DataWord getCallGas(OpCode op, DataWord requestedGas, DataWord availableGas) throws Program.OutOfGasException {
DataWord maxAllowed = Utils.allButOne64th(availableGas);
return requestedGas.compareTo(maxAllowed) > 0 ? maxAllowed : requestedGas;
}
@Override
public DataWord getCreateGas(DataWord availableGas) {
return Utils.allButOne64th(availableGas);
}
@Override
public Constants getConstants() {
return parent.getConstants();
}
@Override
public MinerIfc getMineAlgorithm(SystemProperties config) {
return parent.getMineAlgorithm(config);
}
@Override
public BigInteger calcDifficulty(BlockHeader curBlock, BlockHeader parent) {
return this.parent.calcDifficulty(curBlock, parent);
}
@Override
public BigInteger getCalcDifficultyMultiplier(BlockHeader curBlock, BlockHeader parent) {
return this.parent.getCalcDifficultyMultiplier(curBlock, parent);
}
@Override
public long getTransactionCost(Transaction tx) {
return parent.getTransactionCost(tx);
}
@Override
public boolean acceptTransactionSignature(Transaction tx) {
return parent.acceptTransactionSignature(tx) && tx.getChainId() == null;
}
@Override
public String validateTransactionChanges(BlockStore blockStore, Block curBlock, Transaction tx, Repository repository) {
return parent.validateTransactionChanges(blockStore, curBlock, tx, repository);
}
@Override
public void hardForkTransfers(Block block, Repository repo) {
parent.hardForkTransfers(block, repo);
}
@Override
public byte[] getExtraData(byte[] minerExtraData, long blockNumber) {
return parent.getExtraData(minerExtraData, blockNumber);
}
@Override
public List<Pair<Long, BlockHeaderValidator>> headerValidators() {
return parent.headerValidators();
}
@Override
public boolean eip161() {
return parent.eip161();
}
@Override
public GasCost getGasCost() {
return NEW_GAS_COST;
}
@Override
public BlockchainConfig getConfigForBlock(long blockNumber) {
return this;
}
@Override
public Constants getCommonConstants() {
return getConstants();
}
@Override
public Integer getChainId() {
return null;
}
@Override
public boolean eip198() {
return parent.eip198();
}
@Override
public boolean eip206() {
return false;
}
@Override
public boolean eip211() {
return false;
}
@Override
public boolean eip212() {
return parent.eip212();
}
@Override
public boolean eip213() {
return parent.eip213();
}
@Override
public boolean eip214() {
return false;
}
@Override
public boolean eip658() {
return false;
}
@Override
public boolean eip145() {
return false;
}
@Override
public boolean eip1052() {
return false;
}
@Override
public boolean eip1283() {
return false;
}
@Override
public boolean eip1014() {
return false;
}
@Override
public String toString() {
return getClass().getSimpleName();
}
}
| 5,741
| 26.342857
| 124
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/config/blockchain/DaoHFConfig.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.config.blockchain;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.ethereum.config.BlockchainConfig;
import org.ethereum.core.Block;
import org.ethereum.core.Repository;
import org.spongycastle.util.encoders.Hex;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Anton Nashatyrev on 18.07.2016.
*/
public class DaoHFConfig extends AbstractDaoConfig {
private final List<byte[]> daoAccounts = new ArrayList<>();
private final byte[] withdrawAccount = Hex.decode("bf4ed7b27f1d666546e30d74d50d173d20bca754");
{
supportFork = true;
}
public DaoHFConfig() {
initDaoConfig(new HomesteadConfig(), ETH_FORK_BLOCK_NUMBER);
}
public DaoHFConfig(BlockchainConfig parent, long forkBlockNumber) {
initDaoConfig(parent, forkBlockNumber);
}
@Override
protected void initDaoConfig(BlockchainConfig parent, long forkBlockNumber) {
super.initDaoConfig(parent, forkBlockNumber);
try {
ObjectMapper objectMapper = new ObjectMapper();
DaoAcct[] daoAccts = objectMapper.readValue(accountsJson.replace('\'', '"'), DaoAcct[].class);
for (DaoAcct daoAcct : daoAccts) {
daoAccounts.add(Hex.decode(daoAcct.address.substring(2)));
daoAccounts.add(Hex.decode(daoAcct.extraBalanceAccount.substring(2)));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Goal is to transfer balance from set of accounts to single refund one.
* Accounts may not exists in tests. However refund account should be created anyway.
*/
@Override
public void hardForkTransfers(Block block, Repository repo) {
if (block.getNumber() == forkBlockNumber) {
repo.addBalance(withdrawAccount, BigInteger.ZERO);
for (byte[] account : daoAccounts) {
if (repo.isExist(account)) {
BigInteger balance = repo.getBalance(account);
repo.addBalance(account, balance.negate());
repo.addBalance(withdrawAccount, balance);
}
}
}
}
private static class DaoAcct {
public String address;
public String extraBalanceAccount;
}
private static final String accountsJson = "" +
"[ " +
" { " +
" 'address':'0xd4fe7bc31cedb7bfb8a345f31e668033056b2728'," +
" 'extraBalanceAccount':'0xb3fb0e5aba0e20e5c49d252dfd30e102b171a425'" +
" }," +
" { " +
" 'address':'0x2c19c7f9ae8b751e37aeb2d93a699722395ae18f'," +
" 'extraBalanceAccount':'0xecd135fa4f61a655311e86238c92adcd779555d2'" +
" }," +
" { " +
" 'address':'0x1975bd06d486162d5dc297798dfc41edd5d160a7'," +
" 'extraBalanceAccount':'0xa3acf3a1e16b1d7c315e23510fdd7847b48234f6'" +
" }," +
" { " +
" 'address':'0x319f70bab6845585f412ec7724b744fec6095c85'," +
" 'extraBalanceAccount':'0x06706dd3f2c9abf0a21ddcc6941d9b86f0596936'" +
" }," +
" { " +
" 'address':'0x5c8536898fbb74fc7445814902fd08422eac56d0'," +
" 'extraBalanceAccount':'0x6966ab0d485353095148a2155858910e0965b6f9'" +
" }," +
" { " +
" 'address':'0x779543a0491a837ca36ce8c635d6154e3c4911a6'," +
" 'extraBalanceAccount':'0x2a5ed960395e2a49b1c758cef4aa15213cfd874c'" +
" }," +
" { " +
" 'address':'0x5c6e67ccd5849c0d29219c4f95f1a7a93b3f5dc5'," +
" 'extraBalanceAccount':'0x9c50426be05db97f5d64fc54bf89eff947f0a321'" +
" }," +
" { " +
" 'address':'0x200450f06520bdd6c527622a273333384d870efb'," +
" 'extraBalanceAccount':'0xbe8539bfe837b67d1282b2b1d61c3f723966f049'" +
" }," +
" { " +
" 'address':'0x6b0c4d41ba9ab8d8cfb5d379c69a612f2ced8ecb'," +
" 'extraBalanceAccount':'0xf1385fb24aad0cd7432824085e42aff90886fef5'" +
" }," +
" { " +
" 'address':'0xd1ac8b1ef1b69ff51d1d401a476e7e612414f091'," +
" 'extraBalanceAccount':'0x8163e7fb499e90f8544ea62bbf80d21cd26d9efd'" +
" }," +
" { " +
" 'address':'0x51e0ddd9998364a2eb38588679f0d2c42653e4a6'," +
" 'extraBalanceAccount':'0x627a0a960c079c21c34f7612d5d230e01b4ad4c7'" +
" }," +
" { " +
" 'address':'0xf0b1aa0eb660754448a7937c022e30aa692fe0c5'," +
" 'extraBalanceAccount':'0x24c4d950dfd4dd1902bbed3508144a54542bba94'" +
" }," +
" { " +
" 'address':'0x9f27daea7aca0aa0446220b98d028715e3bc803d'," +
" 'extraBalanceAccount':'0xa5dc5acd6a7968a4554d89d65e59b7fd3bff0f90'" +
" }," +
" { " +
" 'address':'0xd9aef3a1e38a39c16b31d1ace71bca8ef58d315b'," +
" 'extraBalanceAccount':'0x63ed5a272de2f6d968408b4acb9024f4cc208ebf'" +
" }," +
" { " +
" 'address':'0x6f6704e5a10332af6672e50b3d9754dc460dfa4d'," +
" 'extraBalanceAccount':'0x77ca7b50b6cd7e2f3fa008e24ab793fd56cb15f6'" +
" }," +
" { " +
" 'address':'0x492ea3bb0f3315521c31f273e565b868fc090f17'," +
" 'extraBalanceAccount':'0x0ff30d6de14a8224aa97b78aea5388d1c51c1f00'" +
" }," +
" { " +
" 'address':'0x9ea779f907f0b315b364b0cfc39a0fde5b02a416'," +
" 'extraBalanceAccount':'0xceaeb481747ca6c540a000c1f3641f8cef161fa7'" +
" }," +
" { " +
" 'address':'0xcc34673c6c40e791051898567a1222daf90be287'," +
" 'extraBalanceAccount':'0x579a80d909f346fbfb1189493f521d7f48d52238'" +
" }," +
" { " +
" 'address':'0xe308bd1ac5fda103967359b2712dd89deffb7973'," +
" 'extraBalanceAccount':'0x4cb31628079fb14e4bc3cd5e30c2f7489b00960c'" +
" }," +
" { " +
" 'address':'0xac1ecab32727358dba8962a0f3b261731aad9723'," +
" 'extraBalanceAccount':'0x4fd6ace747f06ece9c49699c7cabc62d02211f75'" +
" }," +
" { " +
" 'address':'0x440c59b325d2997a134c2c7c60a8c61611212bad'," +
" 'extraBalanceAccount':'0x4486a3d68fac6967006d7a517b889fd3f98c102b'" +
" }," +
" { " +
" 'address':'0x9c15b54878ba618f494b38f0ae7443db6af648ba'," +
" 'extraBalanceAccount':'0x27b137a85656544b1ccb5a0f2e561a5703c6a68f'" +
" }," +
" { " +
" 'address':'0x21c7fdb9ed8d291d79ffd82eb2c4356ec0d81241'," +
" 'extraBalanceAccount':'0x23b75c2f6791eef49c69684db4c6c1f93bf49a50'" +
" }," +
" { " +
" 'address':'0x1ca6abd14d30affe533b24d7a21bff4c2d5e1f3b'," +
" 'extraBalanceAccount':'0xb9637156d330c0d605a791f1c31ba5890582fe1c'" +
" }," +
" { " +
" 'address':'0x6131c42fa982e56929107413a9d526fd99405560'," +
" 'extraBalanceAccount':'0x1591fc0f688c81fbeb17f5426a162a7024d430c2'" +
" }," +
" { " +
" 'address':'0x542a9515200d14b68e934e9830d91645a980dd7a'," +
" 'extraBalanceAccount':'0xc4bbd073882dd2add2424cf47d35213405b01324'" +
" }," +
" { " +
" 'address':'0x782495b7b3355efb2833d56ecb34dc22ad7dfcc4'," +
" 'extraBalanceAccount':'0x58b95c9a9d5d26825e70a82b6adb139d3fd829eb'" +
" }," +
" { " +
" 'address':'0x3ba4d81db016dc2890c81f3acec2454bff5aada5'," +
" 'extraBalanceAccount':'0xb52042c8ca3f8aa246fa79c3feaa3d959347c0ab'" +
" }," +
" { " +
" 'address':'0xe4ae1efdfc53b73893af49113d8694a057b9c0d1'," +
" 'extraBalanceAccount':'0x3c02a7bc0391e86d91b7d144e61c2c01a25a79c5'" +
" }," +
" { " +
" 'address':'0x0737a6b837f97f46ebade41b9bc3e1c509c85c53'," +
" 'extraBalanceAccount':'0x97f43a37f595ab5dd318fb46e7a155eae057317a'" +
" }," +
" { " +
" 'address':'0x52c5317c848ba20c7504cb2c8052abd1fde29d03'," +
" 'extraBalanceAccount':'0x4863226780fe7c0356454236d3b1c8792785748d'" +
" }," +
" { " +
" 'address':'0x5d2b2e6fcbe3b11d26b525e085ff818dae332479'," +
" 'extraBalanceAccount':'0x5f9f3392e9f62f63b8eac0beb55541fc8627f42c'" +
" }," +
" { " +
" 'address':'0x057b56736d32b86616a10f619859c6cd6f59092a'," +
" 'extraBalanceAccount':'0x9aa008f65de0b923a2a4f02012ad034a5e2e2192'" +
" }," +
" { " +
" 'address':'0x304a554a310c7e546dfe434669c62820b7d83490'," +
" 'extraBalanceAccount':'0x914d1b8b43e92723e64fd0a06f5bdb8dd9b10c79'" +
" }," +
" { " +
" 'address':'0x4deb0033bb26bc534b197e61d19e0733e5679784'," +
" 'extraBalanceAccount':'0x07f5c1e1bc2c93e0402f23341973a0e043f7bf8a'" +
" }," +
" { " +
" 'address':'0x35a051a0010aba705c9008d7a7eff6fb88f6ea7b'," +
" 'extraBalanceAccount':'0x4fa802324e929786dbda3b8820dc7834e9134a2a'" +
" }," +
" { " +
" 'address':'0x9da397b9e80755301a3b32173283a91c0ef6c87e'," +
" 'extraBalanceAccount':'0x8d9edb3054ce5c5774a420ac37ebae0ac02343c6'" +
" }," +
" { " +
" 'address':'0x0101f3be8ebb4bbd39a2e3b9a3639d4259832fd9'," +
" 'extraBalanceAccount':'0x5dc28b15dffed94048d73806ce4b7a4612a1d48f'" +
" }," +
" { " +
" 'address':'0xbcf899e6c7d9d5a215ab1e3444c86806fa854c76'," +
" 'extraBalanceAccount':'0x12e626b0eebfe86a56d633b9864e389b45dcb260'" +
" }," +
" { " +
" 'address':'0xa2f1ccba9395d7fcb155bba8bc92db9bafaeade7'," +
" 'extraBalanceAccount':'0xec8e57756626fdc07c63ad2eafbd28d08e7b0ca5'" +
" }," +
" { " +
" 'address':'0xd164b088bd9108b60d0ca3751da4bceb207b0782'," +
" 'extraBalanceAccount':'0x6231b6d0d5e77fe001c2a460bd9584fee60d409b'" +
" }," +
" { " +
" 'address':'0x1cba23d343a983e9b5cfd19496b9a9701ada385f'," +
" 'extraBalanceAccount':'0xa82f360a8d3455c5c41366975bde739c37bfeb8a'" +
" }," +
" { " +
" 'address':'0x9fcd2deaff372a39cc679d5c5e4de7bafb0b1339'," +
" 'extraBalanceAccount':'0x005f5cee7a43331d5a3d3eec71305925a62f34b6'" +
" }," +
" { " +
" 'address':'0x0e0da70933f4c7849fc0d203f5d1d43b9ae4532d'," +
" 'extraBalanceAccount':'0xd131637d5275fd1a68a3200f4ad25c71a2a9522e'" +
" }," +
" { " +
" 'address':'0xbc07118b9ac290e4622f5e77a0853539789effbe'," +
" 'extraBalanceAccount':'0x47e7aa56d6bdf3f36be34619660de61275420af8'" +
" }," +
" { " +
" 'address':'0xacd87e28b0c9d1254e868b81cba4cc20d9a32225'," +
" 'extraBalanceAccount':'0xadf80daec7ba8dcf15392f1ac611fff65d94f880'" +
" }," +
" { " +
" 'address':'0x5524c55fb03cf21f549444ccbecb664d0acad706'," +
" 'extraBalanceAccount':'0x40b803a9abce16f50f36a77ba41180eb90023925'" +
" }," +
" { " +
" 'address':'0xfe24cdd8648121a43a7c86d289be4dd2951ed49f'," +
" 'extraBalanceAccount':'0x17802f43a0137c506ba92291391a8a8f207f487d'" +
" }," +
" { " +
" 'address':'0x253488078a4edf4d6f42f113d1e62836a942cf1a'," +
" 'extraBalanceAccount':'0x86af3e9626fce1957c82e88cbf04ddf3a2ed7915'" +
" }," +
" { " +
" 'address':'0xb136707642a4ea12fb4bae820f03d2562ebff487'," +
" 'extraBalanceAccount':'0xdbe9b615a3ae8709af8b93336ce9b477e4ac0940'" +
" }," +
" { " +
" 'address':'0xf14c14075d6c4ed84b86798af0956deef67365b5'," +
" 'extraBalanceAccount':'0xca544e5c4687d109611d0f8f928b53a25af72448'" +
" }," +
" { " +
" 'address':'0xaeeb8ff27288bdabc0fa5ebb731b6f409507516c'," +
" 'extraBalanceAccount':'0xcbb9d3703e651b0d496cdefb8b92c25aeb2171f7'" +
" }," +
" { " +
" 'address':'0x6d87578288b6cb5549d5076a207456a1f6a63dc0'," +
" 'extraBalanceAccount':'0xb2c6f0dfbb716ac562e2d85d6cb2f8d5ee87603e'" +
" }," +
" { " +
" 'address':'0xaccc230e8a6e5be9160b8cdf2864dd2a001c28b6'," +
" 'extraBalanceAccount':'0x2b3455ec7fedf16e646268bf88846bd7a2319bb2'" +
" }," +
" { " +
" 'address':'0x4613f3bca5c44ea06337a9e439fbc6d42e501d0a'," +
" 'extraBalanceAccount':'0xd343b217de44030afaa275f54d31a9317c7f441e'" +
" }," +
" { " +
" 'address':'0x84ef4b2357079cd7a7c69fd7a37cd0609a679106'," +
" 'extraBalanceAccount':'0xda2fef9e4a3230988ff17df2165440f37e8b1708'" +
" }," +
" { " +
" 'address':'0xf4c64518ea10f995918a454158c6b61407ea345c'," +
" 'extraBalanceAccount':'0x7602b46df5390e432ef1c307d4f2c9ff6d65cc97'" +
" }," +
" { " +
" 'address':'0xbb9bc244d798123fde783fcc1c72d3bb8c189413'," +
" 'extraBalanceAccount':'0x807640a13483f8ac783c557fcdf27be11ea4ac7a'" +
" }" +
"]";
@Override
public String toString() {
return super.toString() + "(forkBlock:" + forkBlockNumber + ")";
}
}
| 15,684
| 46.530303
| 106
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/config/blockchain/DaoNoHFConfig.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.config.blockchain;
import org.ethereum.config.BlockchainConfig;
/**
* Created by Anton Nashatyrev on 18.07.2016.
*/
public class DaoNoHFConfig extends AbstractDaoConfig {
{
supportFork = false;
}
public DaoNoHFConfig() {
initDaoConfig(new HomesteadConfig(), ETH_FORK_BLOCK_NUMBER);
}
public DaoNoHFConfig(BlockchainConfig parent, long forkBlockNumber) {
initDaoConfig(parent, forkBlockNumber);
}
@Override
public String toString() {
return super.toString() + "(forkBlock:" + forkBlockNumber + ")";
}
}
| 1,389
| 30.590909
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/config/net/MainNetConfig.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.config.net;
import org.ethereum.config.blockchain.*;
/**
* Created by Anton Nashatyrev on 25.02.2016.
*/
public class MainNetConfig extends BaseNetConfig {
public static final MainNetConfig INSTANCE = new MainNetConfig();
public MainNetConfig() {
add(0, new FrontierConfig());
add(1_150_000, new HomesteadConfig());
add(1_920_000, new DaoHFConfig());
add(2_463_000, new Eip150HFConfig(new DaoHFConfig()));
add(2_675_000, new Eip160HFConfig(new DaoHFConfig()));
add(4_370_000, new ByzantiumConfig(new DaoHFConfig()));
add(7_280_000, new PetersburgConfig(new DaoHFConfig()));
}
}
| 1,462
| 37.5
| 80
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.