file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
Identity.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/Identity.java | package org.consenlabs.tokencore.wallet;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.Utils;
import org.bitcoinj.core.VarInt;
import org.consenlabs.tokencore.foundation.crypto.AES;
import org.consenlabs.tokencore.foundation.crypto.Crypto;
import org.consenlabs.tokencore.foundation.crypto.Hash;
import org.consenlabs.tokencore.foundation.crypto.Multihash;
import org.consenlabs.tokencore.foundation.utils.ByteUtil;
import org.consenlabs.tokencore.foundation.utils.MnemonicUtil;
import org.consenlabs.tokencore.foundation.utils.NumericUtil;
import org.consenlabs.tokencore.wallet.keystore.*;
import org.consenlabs.tokencore.wallet.model.*;
import org.consenlabs.tokencore.wallet.transaction.EthereumSign;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.SignatureException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
/**
* Created by xyz on 2017/12/11.
*/
public class Identity {
public static Identity currentIdentity;
public static final String TAG = "Identity";
private static final String FILE_NAME = "identity.json";
private IdentityKeystore keystore;
private List<Wallet> wallets = new ArrayList<>();
public String getIdentifier() {
return this.keystore.getIdentifier();
}
public String getIpfsId() {
return this.keystore.getIpfsId();
}
public List<Wallet> getWallets() {
return this.wallets;
}
public Metadata getMetadata() {
return keystore.getMetadata();
}
public static Identity getCurrentIdentity() {
synchronized (Identity.class) {
if (currentIdentity == null) {
currentIdentity = tryLoadFromFile();
}
return currentIdentity;
}
}
private Identity(IdentityKeystore keystore) {
this.keystore = keystore;
for (String walletId : this.keystore.getWalletIDs()) {
wallets.add(WalletManager.findWalletById(walletId));
}
}
private Identity(Metadata metadata, List<String> mnemonicCodes, String password) {
String segWit = metadata.getSegWit();
this.keystore = new IdentityKeystore(metadata, mnemonicCodes, password);
addWallet(deriveEthereumWallet(mnemonicCodes, password));
addWallet(deriveBitcoinWallet(mnemonicCodes, password, segWit));
// addWallet(deriveEOSWallet(mnemonicCodes, password));
currentIdentity = this;
}
public static Identity createIdentity(String name, String password, String passwordHit, String network, String segWit) {
List<String> mnemonicCodes = MnemonicUtil.randomMnemonicCodes();
Metadata metadata = new Metadata();
metadata.setName(name);
metadata.setPasswordHint(passwordHit);
metadata.setSource(Metadata.FROM_NEW_IDENTITY);
metadata.setNetwork(network);
metadata.setSegWit(segWit);
Identity identity = new Identity(metadata, mnemonicCodes, password);
currentIdentity = identity;
return identity;
}
public static Identity recoverIdentity(String mnemonic, String name, String password,
String passwordHit, String network, String segWit) {
List<String> mnemonicCodes = Arrays.asList(mnemonic.split(" "));
Metadata metadata = new Metadata();
metadata.setName(name);
metadata.setPasswordHint(passwordHit);
metadata.setSource(Metadata.FROM_RECOVERED_IDENTITY);
metadata.setNetwork(network);
metadata.setSegWit(segWit);
Identity identity = new Identity(metadata, mnemonicCodes, password);
currentIdentity = identity;
return identity;
}
public void deleteIdentity(String password) {
if (!this.keystore.verifyPassword(password)) {
throw new TokenException(Messages.WALLET_INVALID_PASSWORD);
}
if (WalletManager.cleanKeystoreDirectory()) {
WalletManager.clearKeystoreMap();
currentIdentity = null;
}
}
public String exportIdentity(String password) {
return this.keystore.decryptMnemonic(password);
}
public void addWallet(Wallet wallet) {
this.keystore.getWalletIDs().add(wallet.getId());
this.wallets.add(wallet);
flush();
}
void removeWallet(String walletId) {
this.keystore.getWalletIDs().remove(walletId);
int idx = 0;
for (; idx < wallets.size(); idx++) {
if (wallets.get(idx).getId().equals(walletId)) {
break;
}
}
this.wallets.remove(idx);
flush();
}
public Wallet deriveWallet(String chainType, String password) {
String mnemonic = exportIdentity(password);
List<String> mnemonics = Arrays.asList(mnemonic.split(" "));
return deriveWalletByMnemonics(chainType,password,mnemonics);
}
public Wallet deriveWalletByMnemonics(String chainType, String password, List<String> mnemonics) {
List<String> chainTypes = new ArrayList<>();
chainTypes.add(chainType);
return deriveWalletsByMnemonics(chainTypes, password, mnemonics).get(0);
}
public List<Wallet> deriveWallets(List<String> chainTypes, String password) {
String mnemonic = exportIdentity(password);
List<String> mnemonics = Arrays.asList(mnemonic.split(" "));
return deriveWalletsByMnemonics(chainTypes, password, mnemonics);
}
public List<Wallet> deriveWalletsByMnemonics(List<String> chainTypes, String password, List<String> mnemonics) {
List<Wallet> wallets = new ArrayList<>();
for (String chainType : chainTypes) {
Wallet wallet;
switch (chainType) {
case ChainType.BITCOIN:
wallet = deriveBitcoinWallet(mnemonics, password, this.getMetadata().getSegWit());
break;
case ChainType.ETHEREUM:
wallet = deriveEthereumWallet(mnemonics, password);
break;
case ChainType.LITECOIN:
wallet = deriveLitecoinWallet(mnemonics, password, this.getMetadata().getSegWit());
break;
case ChainType.DOGECOIN:
wallet = deriveDogecoinWallet(mnemonics, password, this.getMetadata().getSegWit());
break;
case ChainType.DASH:
wallet = deriveDashWallet(mnemonics, password, this.getMetadata().getSegWit());
break;
case ChainType.BITCOINSV:
wallet = deriveBitcoinSVWallet(mnemonics, password, this.getMetadata().getSegWit());
break;
case ChainType.BITCOINCASH:
wallet = deriveBitcoinCASHWallet(mnemonics, password, this.getMetadata().getSegWit());
break;
case ChainType.EOS:
wallet = deriveEOSWallet(mnemonics, password);
break;
case ChainType.TRON:
wallet = deriveTronWallet(mnemonics, password);
break;
case ChainType.FILECOIN:
wallet = deriveFilecoinWallet(mnemonics, password);
break;
default:
throw new TokenException(String.format("Doesn't support deriving %s wallet", chainType));
}
addWallet(wallet);
wallets.add(wallet);
}
return wallets;
}
private static Identity tryLoadFromFile() {
try {
File file = new File(WalletManager.getDefaultKeyDirectory(), FILE_NAME);
ObjectMapper mapper = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
IdentityKeystore keystore = mapper.readValue(file, IdentityKeystore.class);
return new Identity(keystore);
} catch (IOException ignored) {
return null;
}
}
private void flush() {
try {
File file = new File(WalletManager.getDefaultKeyDirectory(), FILE_NAME);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.writeValue(file, this.keystore);
} catch (IOException ex) {
throw new TokenException(Messages.WALLET_STORE_FAIL, ex);
}
}
private Wallet deriveBitcoinWallet(List<String> mnemonicCodes, String password, String segWit) {
Metadata walletMetadata = new Metadata();
walletMetadata.setChainType(ChainType.BITCOIN);
walletMetadata.setPasswordHint(this.getMetadata().getPasswordHint());
walletMetadata.setSource(this.getMetadata().getSource());
walletMetadata.setNetwork(this.getMetadata().getNetwork());
walletMetadata.setName("BTC");
walletMetadata.setSegWit(segWit);
String path;
if (Metadata.P2WPKH.equals(segWit)) {
path = this.getMetadata().isMainNet() ? BIP44Util.BITCOIN_SEGWIT_MAIN_PATH : BIP44Util.BITCOIN_SEGWIT_TESTNET_PATH;
} else {
path = this.getMetadata().isMainNet() ? BIP44Util.BITCOIN_MAINNET_PATH : BIP44Util.BITCOIN_TESTNET_PATH;
}
IMTKeystore keystore = HDMnemonicKeystore.create(walletMetadata, password, mnemonicCodes, path);
return WalletManager.createWallet(keystore);
}
private Wallet deriveLitecoinWallet(List<String> mnemonics, String password, String segWit) {
Metadata walletMetadata = new Metadata();
walletMetadata.setChainType(ChainType.LITECOIN);
walletMetadata.setPasswordHint(this.getMetadata().getPasswordHint());
walletMetadata.setSource(this.getMetadata().getSource());
walletMetadata.setNetwork(this.getMetadata().getNetwork());
walletMetadata.setName("LTC");
walletMetadata.setSegWit(segWit);
String path = BIP44Util.LITECOIN_MAINNET_PATH;
IMTKeystore keystore = HDMnemonicKeystore.create(walletMetadata, password, mnemonics, path);
return WalletManager.createWallet(keystore);
}
private Wallet deriveDashWallet(List<String> mnemonics, String password, String segWit) {
Metadata walletMetadata = new Metadata();
walletMetadata.setChainType(ChainType.DASH);
walletMetadata.setPasswordHint(this.getMetadata().getPasswordHint());
walletMetadata.setSource(this.getMetadata().getSource());
walletMetadata.setNetwork(this.getMetadata().getNetwork());
walletMetadata.setName("DASH");
walletMetadata.setSegWit(segWit);
String path = BIP44Util.DASH_MAINNET_PATH;
IMTKeystore keystore = HDMnemonicKeystore.create(walletMetadata, password, mnemonics, path);
return WalletManager.createWallet(keystore);
}
private Wallet deriveBitcoinSVWallet(List<String> mnemonics, String password, String segWit) {
Metadata walletMetadata = new Metadata();
walletMetadata.setChainType(ChainType.BITCOINSV);
walletMetadata.setPasswordHint(this.getMetadata().getPasswordHint());
walletMetadata.setSource(this.getMetadata().getSource());
walletMetadata.setNetwork(this.getMetadata().getNetwork());
walletMetadata.setName("BSV");
walletMetadata.setSegWit(segWit);
String path = BIP44Util.BITCOINSV_MAINNET_PATH;
IMTKeystore keystore = HDMnemonicKeystore.create(walletMetadata, password, mnemonics, path);
return WalletManager.createWallet(keystore);
}
private Wallet deriveBitcoinCASHWallet(List<String> mnemonics, String password, String segWit) {
Metadata walletMetadata = new Metadata();
walletMetadata.setChainType(ChainType.BITCOINCASH);
walletMetadata.setPasswordHint(this.getMetadata().getPasswordHint());
walletMetadata.setSource(this.getMetadata().getSource());
walletMetadata.setNetwork(this.getMetadata().getNetwork());
walletMetadata.setName("BCH");
walletMetadata.setSegWit(segWit);
String path = BIP44Util.BITCOINCASH_MAINNET_PATH;
IMTKeystore keystore = HDMnemonicKeystore.create(walletMetadata, password, mnemonics, path);
return WalletManager.createWallet(keystore);
}
private Wallet deriveDogecoinWallet(List<String> mnemonics, String password, String segWit) {
Metadata walletMetadata = new Metadata();
walletMetadata.setChainType(ChainType.DOGECOIN);
walletMetadata.setPasswordHint(this.getMetadata().getPasswordHint());
walletMetadata.setSource(this.getMetadata().getSource());
walletMetadata.setNetwork(this.getMetadata().getNetwork());
walletMetadata.setName("DOGE");
walletMetadata.setSegWit(segWit);
String path = BIP44Util.DOGECOIN_MAINNET_PATH;
IMTKeystore keystore = HDMnemonicKeystore.create(walletMetadata, password, mnemonics, path);
return WalletManager.createWallet(keystore);
}
private Wallet deriveEthereumWallet(List<String> mnemonics, String password) {
Metadata walletMetadata = new Metadata();
walletMetadata.setChainType(ChainType.ETHEREUM);
walletMetadata.setPasswordHint(this.getMetadata().getPasswordHint());
walletMetadata.setSource(this.getMetadata().getSource());
walletMetadata.setName("ETH");
IMTKeystore keystore = V3MnemonicKeystore.create(walletMetadata, password, mnemonics, BIP44Util.ETHEREUM_PATH);
return WalletManager.createWallet(keystore);
}
private Wallet deriveTronWallet(List<String> mnemonics, String password) {
Metadata walletMetadata = new Metadata();
walletMetadata.setChainType(ChainType.TRON);
walletMetadata.setPasswordHint(this.getMetadata().getPasswordHint());
walletMetadata.setSource(this.getMetadata().getSource());
walletMetadata.setName("TRX");
IMTKeystore keystore = V3MnemonicKeystore.create(walletMetadata, password, mnemonics, BIP44Util.TRON_PATH);
return WalletManager.createWallet(keystore);
}
private Wallet deriveFilecoinWallet(List<String> mnemonics, String password) {
Metadata walletMetadata = new Metadata();
walletMetadata.setChainType(ChainType.FILECOIN);
walletMetadata.setPasswordHint(this.getMetadata().getPasswordHint());
walletMetadata.setSource(this.getMetadata().getSource());
walletMetadata.setName("Filecoin");
IMTKeystore keystore = V3MnemonicKeystore.create(walletMetadata, password, mnemonics, BIP44Util.FILECOIN_PATH);
return WalletManager.createWallet(keystore);
}
private Wallet deriveEOSWallet(List<String> mnemonics, String password) {
Metadata metadata = new Metadata();
metadata.setChainType(ChainType.EOS);
metadata.setPasswordHint(this.getMetadata().getPasswordHint());
metadata.setSource(this.getMetadata().getSource());
metadata.setName("EOS");
IMTKeystore keystore = EOSKeystore.create(metadata, password, "", mnemonics, BIP44Util.EOS_LEDGER, null);
return WalletManager.createWallet(keystore);
}
public String encryptDataToIPFS(String originData) {
long unixTimestamp = Utils.currentTimeSeconds();
byte[] iv = NumericUtil.generateRandomBytes(16);
return encryptDataToIPFS(originData, unixTimestamp, iv);
}
String encryptDataToIPFS(String originData, long unixtime, byte[] iv) {
int headerLength = 21;
byte[] toSign = new byte[headerLength + 32];
byte version = 0x03;
toSign[0] = version;
byte[] timestamp = new byte[4];
Utils.uint32ToByteArrayLE(unixtime, timestamp, 0);
System.arraycopy(timestamp, 0, toSign, 1, 4);
byte[] encryptionKey = NumericUtil.hexToBytes(this.keystore.getEncKey());
System.arraycopy(iv, 0, toSign, 5, 16);
byte[] encKey = Arrays.copyOf(encryptionKey, 16);
byte[] ciphertext = AES.encryptByCBC(originData.getBytes(Charset.forName("UTF-8")), encKey, iv);
VarInt ciphertextLength = new VarInt(ciphertext.length);
System.arraycopy(Hash.merkleHash(ciphertext), 0, toSign, headerLength, 32);
String signature = EthereumSign.sign(NumericUtil.bytesToHex(toSign), encryptionKey);
byte[] signatureBytes = NumericUtil.hexToBytes(signature);
int totalLen = (int) (headerLength + ciphertextLength.getSizeInBytes() + ciphertextLength.value + 65);
byte[] payload = new byte[totalLen];
int destPos = 0;
System.arraycopy(toSign, 0, payload, destPos, headerLength);
destPos += headerLength;
System.arraycopy(ciphertextLength.encode(), 0, payload, destPos, ciphertextLength.getSizeInBytes());
destPos += ciphertextLength.getSizeInBytes();
System.arraycopy(ciphertext, 0, payload, destPos, (int) ciphertextLength.value);
destPos += (int) ciphertextLength.value;
System.arraycopy(signatureBytes, 0, payload, destPos, 65);
return NumericUtil.bytesToHex(payload);
}
public String decryptDataFromIPFS(String encryptedData) {
int headerLength = 21;
byte[] payload = NumericUtil.hexToBytes(encryptedData);
byte version = payload[0];
if (version != 0x03) {
throw new TokenException(Messages.UNSUPPORT_ENCRYPTION_DATA_VERSION);
}
int srcPos = 1;
byte[] toSign = new byte[headerLength + 32];
System.arraycopy(payload, 0, toSign, 0, headerLength);
byte[] timestamp = new byte[4];
System.arraycopy(payload, srcPos, timestamp, 0, 4);
srcPos += 4;
byte[] encryptionKey = NumericUtil.hexToBytes(this.keystore.getEncKey());
byte[] iv = new byte[16];
System.arraycopy(payload, srcPos, iv, 0, 16);
srcPos += 16;
VarInt ciphertextLength = new VarInt(payload, srcPos);
srcPos += ciphertextLength.getSizeInBytes();
byte[] ciphertext = new byte[(int) ciphertextLength.value];
System.arraycopy(payload, srcPos, ciphertext, 0, (int) ciphertextLength.value);
System.arraycopy(Hash.merkleHash(ciphertext), 0, toSign, headerLength, 32);
srcPos += ciphertextLength.value;
byte[] encKey = Arrays.copyOf(encryptionKey, 16);
String content = new String(AES.decryptByCBC(ciphertext, encKey, iv), Charset.forName("UTF-8"));
byte[] signature = new byte[65];
System.arraycopy(payload, srcPos, signature, 0, 65);
try {
BigInteger pubKey = EthereumSign.ecRecover(NumericUtil.bytesToHex(toSign), NumericUtil.bytesToHex(signature));
ECKey ecKey = ECKey.fromPublicOnly(ByteUtil.concat(new byte[]{0x04}, NumericUtil.bigIntegerToBytesWithZeroPadded(pubKey, 64)));
String recoverIpfsID = new Multihash(Multihash.Type.sha2_256, Hash.sha256(ecKey.getPubKey())).toBase58();
if (!this.keystore.getIpfsId().equals(recoverIpfsID)) {
throw new TokenException(Messages.INVALID_ENCRYPTION_DATA_SIGNATURE);
}
} catch (SignatureException e) {
throw new TokenException(Messages.INVALID_ENCRYPTION_DATA_SIGNATURE);
}
return content;
}
public String signAuthenticationMessage(int accessTime, String deviceToken, String password) {
Crypto crypto = this.keystore.getCrypto();
byte[] decrypted = crypto.decryptEncPair(password, this.keystore.getEncAuthKey());
String data = String.format(Locale.ENGLISH, "%d.%s.%s", accessTime, getIdentifier(), deviceToken);
return EthereumSign.sign(data, decrypted);
}
}
| 20,177 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
Wallet.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/Wallet.java | package org.consenlabs.tokencore.wallet;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.HexUtil;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.bitcoinj.crypto.ChildNumber;
import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.crypto.HDKeyDerivation;
import org.consenlabs.tokencore.foundation.utils.MetaUtil;
import org.consenlabs.tokencore.foundation.utils.NumericUtil;
import org.consenlabs.tokencore.wallet.keystore.*;
import org.consenlabs.tokencore.wallet.model.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public class Wallet {
private IMTKeystore keystore;
public IMTKeystore getKeystore() {
return keystore;
}
public Wallet(IMTKeystore keystore) {
this.keystore = keystore;
}
public String getId() {
return this.keystore.getId();
}
public String getAddress() {
return this.keystore.getAddress();
}
public Metadata getMetadata() {
return keystore.getMetadata();
}
public String getEncXPub() {
if (keystore instanceof HDMnemonicKeystore) {
return ((HDMnemonicKeystore) keystore).getEncryptXPub();
}
return null;
}
public byte[] decryptMainKey(String password) {
return keystore.decryptCiphertext(password);
}
MnemonicAndPath exportMnemonic(String password) {
if (keystore instanceof EncMnemonicKeystore) {
EncMnemonicKeystore encMnemonicKeystore = (EncMnemonicKeystore) keystore;
String mnemonic = encMnemonicKeystore.decryptMnemonic(password);
String path = encMnemonicKeystore.getMnemonicPath();
return new MnemonicAndPath(mnemonic, path);
}
return null;
}
String exportKeystore(String password) {
if (keystore instanceof ExportableKeystore) {
if (!keystore.verifyPassword(password)) {
throw new TokenException(Messages.WALLET_INVALID_PASSWORD);
}
try {
ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(IMTKeystore.class, V3Ignore.class);
return mapper.writeValueAsString(keystore);
} catch (Exception ex) {
throw new TokenException(Messages.WALLET_INVALID, ex);
}
} else {
throw new TokenException(Messages.CAN_NOT_EXPORT_MNEMONIC);
}
}
public String exportPrivateKey(String password) {
if (keystore instanceof V3Keystore || keystore instanceof V3MnemonicKeystore) {
byte[] decrypted = keystore.decryptCiphertext(password);
if (keystore.getMetadata().getSource().equals(Metadata.FROM_WIF)) {
return new String(decrypted);
} else if (keystore.getMetadata().getChainType().equals(ChainType.FILECOIN)) {
String base64Key = Base64.encode(decrypted);
HashMap<String, String> map = new HashMap<>();
map.put("Type", "secp256k1");
map.put("PrivateKey", base64Key);
String json = JSON.toJSONString(map);
return NumericUtil.bytesToHex(json.getBytes());
} else {
return NumericUtil.bytesToHex(decrypted);
}
} else if (keystore instanceof HDMnemonicKeystore) {
String xprv = new String(decryptMainKey(password), Charset.forName("UTF-8"));
DeterministicKey xprvKey = DeterministicKey.deserializeB58(xprv, MetaUtil.getNetWork(keystore.getMetadata()));
DeterministicKey accountKey = HDKeyDerivation.deriveChildKey(xprvKey, new ChildNumber(0, false));
DeterministicKey externalChangeKey = HDKeyDerivation.deriveChildKey(accountKey, new ChildNumber(0, false));
return NumericUtil.bigIntegerToHex(externalChangeKey.getPrivKey());
}
throw new TokenException(Messages.ILLEGAL_OPERATION);
}
boolean verifyPassword(String password) {
return keystore.verifyPassword(password);
}
public byte[] decryptPrvKeyFor(String pubKey, String password) {
if (!(keystore instanceof EOSKeystore)) {
throw new TokenException("This method is only for EOS wallet!");
}
EOSKeystore eosKeystore = (EOSKeystore) keystore;
return eosKeystore.decryptPrivateKeyFor(pubKey, password);
}
public String newReceiveAddress(int nextRecvIdx) {
if (keystore instanceof HDMnemonicKeystore) {
return ((HDMnemonicKeystore) keystore).newReceiveAddress(nextRecvIdx);
} else {
return keystore.getAddress();
}
}
public long getCreatedAt() {
return this.keystore.getMetadata().getTimestamp();
}
boolean hasMnemonic() {
return this.keystore instanceof EncMnemonicKeystore;
}
public List<KeyPair> exportPrivateKeys(String password) {
if (keystore instanceof EOSKeystore) {
return ((EOSKeystore) keystore).exportPrivateKeys(password);
} else if (keystore instanceof LegacyEOSKeystore) {
return ((LegacyEOSKeystore) keystore).exportPrivateKeys(password);
} else {
throw new TokenException("Only eos wallet can export multi private keys");
}
}
public void setAccountName(String accountName) {
if (!(keystore instanceof EOSKeystore)) {
throw new TokenException("Only EOS wallet can update account name!");
}
((EOSKeystore) keystore).setAccountName(accountName);
}
public List<EOSKeystore.KeyPathPrivate> getKeyPathPrivates() {
if (keystore instanceof EOSKeystore) {
return ((EOSKeystore) keystore).getKeyPathPrivates();
} else if (keystore instanceof LegacyEOSKeystore) {
return Collections.emptyList();
} else {
throw new TokenException("Only EOS wallet can export all public keys!");
}
}
boolean delete(String password) {
return keystore.verifyPassword(password) && WalletManager.generateWalletFile(keystore.getId()).delete();
}
}
| 6,437 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
KeystoreStorage.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/KeystoreStorage.java | package org.consenlabs.tokencore.wallet;
import java.io.File;
/**
* Created by xyz on 2018/4/8.
*/
public interface KeystoreStorage {
File getKeystoreDir();
}
| 177 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
WalletManager.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/WalletManager.java | package org.consenlabs.tokencore.wallet;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import com.google.common.io.CharSource;
import com.google.common.io.Files;
import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.wallet.DeterministicKeyChain;
import org.bitcoinj.wallet.DeterministicSeed;
import org.consenlabs.tokencore.foundation.utils.MnemonicUtil;
import org.consenlabs.tokencore.foundation.utils.NumericUtil;
import org.consenlabs.tokencore.wallet.address.AddressCreatorManager;
import org.consenlabs.tokencore.wallet.address.EthereumAddressCreator;
import org.consenlabs.tokencore.wallet.keystore.*;
import org.consenlabs.tokencore.wallet.model.*;
import org.consenlabs.tokencore.wallet.validators.PrivateKeyValidator;
import org.json.JSONObject;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.List;
public class WalletManager {
private static Hashtable<String, IMTKeystore> keystoreMap = new Hashtable<>();
private static final String LOG_TAG = WalletManager.class.getSimpleName();
public static KeystoreStorage storage;
//
// static {
// try {ø
// scanWallets();
// } catch (IOException ignored) {
// }
// }
static Wallet createWallet(IMTKeystore keystore) {
File file = generateWalletFile(keystore.getId());
writeToFile(keystore, file);
keystoreMap.put(keystore.getId(), keystore);
return new Wallet(keystore);
}
public static Hashtable<String, IMTKeystore> getKeyMap(){
return keystoreMap;
}
public static void changePassword(String id, String oldPassword, String newPassword) {
IMTKeystore keystore = mustFindKeystoreById(id);
IMTKeystore newKeystore = (IMTKeystore) keystore.changePassword(oldPassword, newPassword);
flushWallet(newKeystore, true);
}
public static String exportPrivateKey(String id, String password) {
Wallet wallet = mustFindWalletById(id);
return wallet.exportPrivateKey(password);
}
public static List<KeyPair> exportPrivateKeys(String id, String password) {
Wallet wallet = mustFindWalletById(id);
return wallet.exportPrivateKeys(password);
}
public static MnemonicAndPath exportMnemonic(String id, String password) {
Wallet wallet = mustFindWalletById(id);
return wallet.exportMnemonic(password);
}
public static String exportKeystore(String id, String password) {
Wallet wallet = mustFindWalletById(id);
return wallet.exportKeystore(password);
}
public static void removeWallet(String id, String password) {
Wallet wallet = mustFindWalletById(id);
if (!wallet.verifyPassword(password)) {
throw new TokenException(Messages.WALLET_INVALID_PASSWORD);
}
if (wallet.delete(password)) {
Identity.getCurrentIdentity().removeWallet(id);
keystoreMap.remove(id);
}
}
public static void clearKeystoreMap() {
keystoreMap.clear();
}
public static Wallet importWalletFromKeystore(Metadata metadata, String keystoreContent, String password, boolean overwrite) {
WalletKeystore importedKeystore = validateKeystore(keystoreContent, password);
if (metadata.getSource() == null)
metadata.setSource(Metadata.FROM_KEYSTORE);
String privateKey = NumericUtil.bytesToHex(importedKeystore.decryptCiphertext(password));
try {
new PrivateKeyValidator(privateKey).validate();
} catch (TokenException ex) {
if (Messages.PRIVATE_KEY_INVALID.equals(ex.getMessage())) {
throw new TokenException(Messages.KEYSTORE_CONTAINS_INVALID_PRIVATE_KEY);
} else {
throw ex;
}
}
return importWalletFromPrivateKey(metadata, privateKey, password, overwrite);
}
public static Wallet importWalletFromPrivateKey(Metadata metadata, String prvKeyHex, String password, boolean overwrite) {
IMTKeystore keystore = V3Keystore.create(metadata, password, prvKeyHex);
Wallet wallet = flushWallet(keystore, overwrite);
Identity.getCurrentIdentity().addWallet(wallet);
return wallet;
}
/**
* Just for import EOS wallet
*/
public static Wallet importWalletFromPrivateKeys(Metadata metadata, String accountName, List<String> prvKeys, List<EOSKeystore.PermissionObject> permissions, String password, boolean overwrite) {
IMTKeystore keystore = null;
if (!ChainType.EOS.equalsIgnoreCase(metadata.getChainType())) {
throw new TokenException("This method is only for importing EOS wallet");
}
keystore = EOSKeystore.create(metadata, password, accountName, prvKeys, permissions);
return persistWallet(keystore, overwrite);
}
/**
* use the importWalletFromPrivateKeys
*/
@Deprecated
public static Wallet importWalletFromPrivateKey(Metadata metadata, String accountName, String prvKeyHex, String password, boolean overwrite) {
IMTKeystore keystore = LegacyEOSKeystore.create(metadata, accountName, password, prvKeyHex);
return persistWallet(keystore, overwrite);
}
/**
* import wallet from mnemonic
*
* @param metadata
* @param accountName only for EOS
* @param mnemonic
* @param path
* @param permissions only for EOS
* @param password
* @param overwrite
* @return
*/
public static Wallet importWalletFromMnemonic(Metadata metadata, @Nullable String accountName, String mnemonic, String path, @Nullable List<EOSKeystore.PermissionObject> permissions, String password, boolean overwrite) {
if (metadata.getSource() == null)
metadata.setSource(Metadata.FROM_MNEMONIC);
IMTKeystore keystore = null;
List<String> mnemonicCodes = Arrays.asList(mnemonic.split(" "));
MnemonicUtil.validateMnemonics(mnemonicCodes);
switch (metadata.getChainType()) {
case ChainType.ETHEREUM:
keystore = V3MnemonicKeystore.create(metadata, password, mnemonicCodes, path);
break;
case ChainType.BITCOIN:
keystore = HDMnemonicKeystore.create(metadata, password, mnemonicCodes, path);
break;
case ChainType.LITECOIN:
keystore = HDMnemonicKeystore.create(metadata, password, mnemonicCodes, path);
break;
case ChainType.EOS:
keystore = EOSKeystore.create(metadata, password, accountName, mnemonicCodes, path, permissions);
}
return persistWallet(keystore, overwrite);
}
public static Wallet importWalletFromMnemonic(Metadata metadata, String mnemonic, String path, String password, boolean overwrite) {
return importWalletFromMnemonic(metadata, null, mnemonic, path, null, password, overwrite);
}
public static Wallet findWalletByPrivateKey(String chainType, String network, String privateKey, String segWit) {
if (ChainType.ETHEREUM.equals(chainType)) {
new PrivateKeyValidator(privateKey).validate();
}
Network net = new Network(network);
String address = AddressCreatorManager.getInstance(chainType, net.isMainnet(), segWit).fromPrivateKey(privateKey);
return findWalletByAddress(chainType, address);
}
public static Wallet findWalletByKeystore(String chainType, String keystoreContent, String password) {
WalletKeystore walletKeystore = validateKeystore(keystoreContent, password);
byte[] prvKeyBytes = walletKeystore.decryptCiphertext(password);
String address = new EthereumAddressCreator().fromPrivateKey(prvKeyBytes);
return findWalletByAddress(chainType, address);
}
public static Wallet findWalletByMnemonic(String chainType, String network, String mnemonic, String path, String segWit) {
List<String> mnemonicCodes = Arrays.asList(mnemonic.split(" "));
MnemonicUtil.validateMnemonics(mnemonicCodes);
DeterministicSeed seed = new DeterministicSeed(mnemonicCodes, null, "", 0L);
DeterministicKeyChain keyChain = DeterministicKeyChain.builder().seed(seed).build();
if (Strings.isNullOrEmpty(path)) {
throw new TokenException(Messages.INVALID_MNEMONIC_PATH);
}
if (ChainType.BITCOIN.equalsIgnoreCase(chainType)||ChainType.LITECOIN.equalsIgnoreCase(chainType)) {
path += "/0/0";
}
DeterministicKey key = keyChain.getKeyByPath(BIP44Util.generatePath(path), true);
Network net = new Network(network);
String address = AddressCreatorManager.getInstance(chainType, net.isMainnet(), segWit).fromPrivateKey(key.getPrivateKeyAsHex());
return findWalletByAddress(chainType, address);
}
public static Wallet switchBTCWalletMode(String id, String password, String model) {
Wallet wallet = mustFindWalletById(id);
// !!! Warning !!! You must verify password before you write content to keystore
if (!wallet.getMetadata().getChainType().equalsIgnoreCase(ChainType.BITCOIN))
throw new TokenException("Ethereum wallet can't switch mode");
Metadata metadata = wallet.getMetadata().clone();
if (metadata.getSegWit().equalsIgnoreCase(model)) {
return wallet;
}
metadata.setSegWit(model);
IMTKeystore keystore;
if (wallet.hasMnemonic()) {
MnemonicAndPath mnemonicAndPath = wallet.exportMnemonic(password);
String path = BIP44Util.getBTCMnemonicPath(model, metadata.isMainNet());
List<String> mnemonicCodes = Arrays.asList(mnemonicAndPath.getMnemonic().split(" "));
keystore = new HDMnemonicKeystore(metadata, password, mnemonicCodes, path, wallet.getId());
} else {
String prvKey = wallet.exportPrivateKey(password);
keystore = new V3Keystore(metadata, password, prvKey, wallet.getId());
}
flushWallet(keystore, false);
keystoreMap.put(wallet.getId(), keystore);
return new Wallet(keystore);
}
public static Wallet setAccountName(String id, String accountName) {
Wallet wallet = mustFindWalletById(id);
wallet.setAccountName(accountName);
return persistWallet(wallet.getKeystore(), true);
}
static Wallet findWalletById(String id) {
IMTKeystore keystore = keystoreMap.get(id);
if (keystore != null) {
return new Wallet(keystore);
} else {
return null;
}
}
public static Wallet mustFindWalletById(String id) {
IMTKeystore keystore = keystoreMap.get(id);
if (keystore == null) throw new TokenException(Messages.WALLET_NOT_FOUND);
return new Wallet(keystore);
}
static File generateWalletFile(String walletID) {
return new File(getDefaultKeyDirectory(), walletID + ".json");
}
static File getDefaultKeyDirectory() {
File directory = new File(storage.getKeystoreDir(), "wallets");
if (!directory.exists()) {
directory.mkdirs();
}
return directory;
}
static boolean cleanKeystoreDirectory() {
return deleteDir(getDefaultKeyDirectory());
}
private static Wallet persistWallet(IMTKeystore keystore, boolean overwrite) {
Wallet wallet = flushWallet(keystore, overwrite);
Identity.getCurrentIdentity().addWallet(wallet);
return wallet;
}
private static IMTKeystore findKeystoreByAddress(String type, String address) {
if (Strings.isNullOrEmpty(address)) return null;
for (IMTKeystore keystore : keystoreMap.values()) {
if (Strings.isNullOrEmpty(keystore.getAddress())) {
continue;
}
if (keystore.getMetadata().getChainType().equals(type) && keystore.getAddress().equals(address)) {
return keystore;
}
}
return null;
}
public static Wallet findWalletByAddress(String type, String address) {
IMTKeystore keystore = findKeystoreByAddress(type, address);
if (keystore != null) {
return new Wallet(keystore);
}
return null;
}
private static Wallet flushWallet(IMTKeystore keystore, boolean overwrite) {
IMTKeystore existsKeystore = findKeystoreByAddress(keystore.getMetadata().getChainType(), keystore.getAddress());
if (existsKeystore != null) {
if (!overwrite) {
throw new TokenException(Messages.WALLET_EXISTS);
} else {
keystore.setId(existsKeystore.getId());
}
}
File file = generateWalletFile(keystore.getId());
writeToFile(keystore, file);
keystoreMap.put(keystore.getId(), keystore);
return new Wallet(keystore);
}
private static void writeToFile(Keystore keyStore, File destination) {
try {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.writeValue(destination, keyStore);
} catch (IOException ex) {
throw new TokenException(Messages.WALLET_STORE_FAIL, ex);
}
}
private static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (String child : children) {
boolean success = deleteDir(new File(dir, child));
if (!success) {
return false;
}
}
}
return dir.delete();
}
private static V3Keystore validateKeystore(String keystoreContent, String password) {
V3Keystore importedKeystore = unmarshalKeystore(keystoreContent, V3Keystore.class);
if (Strings.isNullOrEmpty(importedKeystore.getAddress()) || importedKeystore.getCrypto() == null) {
throw new TokenException(Messages.WALLET_INVALID_KEYSTORE);
}
importedKeystore.getCrypto().validate();
if (!importedKeystore.verifyPassword(password))
throw new TokenException(Messages.MAC_UNMATCH);
byte[] prvKey = importedKeystore.decryptCiphertext(password);
String address = new EthereumAddressCreator().fromPrivateKey(prvKey);
if (Strings.isNullOrEmpty(address) || !address.equalsIgnoreCase(importedKeystore.getAddress())) {
throw new TokenException(Messages.PRIVATE_KEY_ADDRESS_NOT_MATCH);
}
return importedKeystore;
}
private static IMTKeystore mustFindKeystoreById(String id) {
IMTKeystore keystore = keystoreMap.get(id);
if (keystore == null) {
throw new TokenException(Messages.WALLET_NOT_FOUND);
}
return keystore;
}
private static <T extends WalletKeystore> T unmarshalKeystore(String keystoreContent, Class<T> clazz) {
T importedKeystore;
try {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES, true);
importedKeystore = mapper.readValue(keystoreContent, clazz);
} catch (IOException ex) {
throw new TokenException(Messages.WALLET_INVALID_KEYSTORE, ex);
}
return importedKeystore;
}
public static void scanWallets() {
File directory = getDefaultKeyDirectory();
keystoreMap.clear();
for (File file : directory.listFiles()) {
if (!file.getName().startsWith("identity")) {
try {
IMTKeystore keystore = null;
CharSource charSource = Files.asCharSource(file, Charset.forName("UTF-8"));
String jsonContent = charSource.read();
JSONObject jsonObject = new JSONObject(jsonContent);
int version = jsonObject.getInt("version");
if (version == 3) {
if (jsonContent.contains("encMnemonic")) {
keystore = unmarshalKeystore(jsonContent, V3MnemonicKeystore.class);
} else if (jsonObject.has("imTokenMeta") && ChainType.EOS.equals(jsonObject.getJSONObject("imTokenMeta").getString("chainType"))) {
keystore = unmarshalKeystore(jsonContent, LegacyEOSKeystore.class);
} else {
keystore = unmarshalKeystore(jsonContent, V3Keystore.class);
}
} else if (version == 1) {
keystore = unmarshalKeystore(jsonContent, V3Keystore.class);
} else if (version == 44) {
keystore = unmarshalKeystore(jsonContent, HDMnemonicKeystore.class);
} else if (version == 10001) {
keystore = unmarshalKeystore(jsonContent, EOSKeystore.class);
}
if (keystore != null) {
keystoreMap.put(keystore.getId(), keystore);
}
} catch (Exception ex) {
// log.info(LOG_TAG, "Can't loaded " + file.getName() + " file", ex);
}
}
}
}
private WalletManager() {
}
}
| 18,386 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
WIFValidator.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/validators/WIFValidator.java | package org.consenlabs.tokencore.wallet.validators;
import org.bitcoinj.core.AddressFormatException;
import org.bitcoinj.core.DumpedPrivateKey;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.WrongNetworkException;
import org.consenlabs.tokencore.wallet.model.Messages;
import org.consenlabs.tokencore.wallet.model.TokenException;
/**
* Created by xyz on 2018/2/27.
*/
public final class WIFValidator implements Validator<String> {
String wif;
NetworkParameters network;
boolean requireCompressed = false;
public WIFValidator(String wif, NetworkParameters network) {
this.wif = wif;
this.network = network;
}
public WIFValidator(String wif, NetworkParameters network, boolean requireCompressed) {
this.wif = wif;
this.network = network;
this.requireCompressed = requireCompressed;
}
@Override
public String validate() {
try {
DumpedPrivateKey.fromBase58(network, wif);
} catch (WrongNetworkException addressException) {
throw new TokenException(Messages.WIF_WRONG_NETWORK);
} catch (AddressFormatException addressFormatException) {
throw new TokenException(Messages.WIF_INVALID);
}
if (requireCompressed && !DumpedPrivateKey.fromBase58(network, wif).getKey().isCompressed()) {
throw new TokenException(Messages.SEGWIT_NEEDS_COMPRESS_PUBLIC_KEY);
}
return this.wif;
}
}
| 1,434 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
Validator.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/validators/Validator.java | package org.consenlabs.tokencore.wallet.validators;
/**
* Created by xyz on 2018/2/27.
*/
public interface Validator<T> {
T validate();
}
| 153 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
MetadataValidator.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/validators/MetadataValidator.java | package org.consenlabs.tokencore.wallet.validators;
import com.google.common.base.Strings;
import org.consenlabs.tokencore.wallet.model.ChainType;
import org.consenlabs.tokencore.wallet.model.Metadata;
import java.util.HashMap;
import static com.google.common.base.Preconditions.checkState;
/**
* Created by xyz on 2018/4/10.
*/
public final class MetadataValidator implements Validator<Metadata> {
private HashMap<String, Object> map;
private String source;
public MetadataValidator(HashMap<String, Object> map) {
this.map = map;
}
public MetadataValidator(HashMap<String, Object> map, String source) {
this.map = map;
this.source = source;
}
@Override
public Metadata validate() {
String name = (String) map.get("name");
String passwordHint = (String) map.get("passwordHint");
String chainType = (String) map.get("chainType");
String network = null;
String segWit = null;
if (!ChainType.ETHEREUM.equalsIgnoreCase(chainType)) {
if (map.containsKey("network")) {
network = ((String) map.get("network")).toUpperCase();
}
if (map.containsKey("segWit")) {
segWit = ((String) map.get("segWit")).toUpperCase();
}
}
checkState(!Strings.isNullOrEmpty(name), "Can't allow empty name");
ChainType.validate(chainType);
Metadata metadata = new Metadata(chainType, network, name, passwordHint);
if (!Strings.isNullOrEmpty(this.source)) {
metadata.setSource(this.source);
}
metadata.setSegWit(segWit);
return metadata;
}
} | 1,610 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
ETHAddressValidator.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/validators/ETHAddressValidator.java | package org.consenlabs.tokencore.wallet.validators;
import com.google.common.base.Strings;
import org.consenlabs.tokencore.foundation.crypto.Hash;
import org.consenlabs.tokencore.foundation.utils.NumericUtil;
import org.consenlabs.tokencore.wallet.model.Messages;
import org.consenlabs.tokencore.wallet.model.TokenException;
import java.util.regex.Pattern;
import static com.google.common.base.Preconditions.checkState;
/**
* Created by xyz on 2018/3/12.
*/
public class ETHAddressValidator implements Validator<Void> {
private String address;
private static final Pattern ignoreCaseAddrPattern = Pattern.compile("^(0x)?[0-9a-f]{40}$",
Pattern.CASE_INSENSITIVE);
private static final Pattern lowerCaseAddrPattern = Pattern.compile("^(0x)?[0-9a-f]{40}$");
private static final Pattern upperCaseAddrPattern = Pattern.compile("^(0x)?[0-9A-F]{40}$");
public ETHAddressValidator(String address) {
this.address = address;
}
@Override
public Void validate() {
if (!isValidAddress(this.address)) {
throw new TokenException(Messages.WALLET_INVALID_ADDRESS);
}
return null;
}
private boolean isValidAddress(String address) {
// if not [0-9]{40} return false
if (Strings.isNullOrEmpty(address) || !ignoreCaseAddrPattern.matcher(address).find()) {
return false;
} else if (lowerCaseAddrPattern.matcher(address).find() || upperCaseAddrPattern.matcher(address).find()) {
// if it's all small caps or caps return true
return true;
} else {
// if it is mixed caps it is a checksum address and needs to be validated
return validateChecksumAddress(address);
}
}
private boolean validateChecksumAddress(String address) {
address = NumericUtil.cleanHexPrefix(address);
checkState(address.length() == 40);
String lowerAddress = NumericUtil.cleanHexPrefix(address).toLowerCase();
String hash = NumericUtil.bytesToHex(Hash.keccak256(lowerAddress.getBytes()));
for (int i = 0; i < 40; i++) {
if (Character.isLetter(address.charAt(i))) {
// each uppercase letter should correlate with a first bit of 1 in the hash
// char with the same index, and each lowercase letter with a 0 bit
int charInt = Integer.parseInt(Character.toString(hash.charAt(i)), 16);
if ((Character.isUpperCase(address.charAt(i)) && charInt <= 7)
|| (Character.isLowerCase(address.charAt(i)) && charInt > 7)) {
return false;
}
}
}
return true;
}
}
| 2,591 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
PrivateKeyValidator.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/validators/PrivateKeyValidator.java | package org.consenlabs.tokencore.wallet.validators;
import org.bitcoinj.core.ECKey;
import org.consenlabs.tokencore.foundation.utils.NumericUtil;
import org.consenlabs.tokencore.wallet.model.Messages;
import org.consenlabs.tokencore.wallet.model.TokenException;
import java.math.BigInteger;
/**
* Created by xyz on 2018/2/27.
*/
public final class PrivateKeyValidator implements Validator<String> {
private String privateKey;
public PrivateKeyValidator(String prvKey) {
this.privateKey = prvKey;
}
// todo: BitcoinJ provides a wrapper of NativeSecp256k1, but not provide a workable .so file
// For stability, we do not compile the .so by ourselves, instead, we write some simple java code.
@Override
public String validate() {
try {
// validating private key
BigInteger pkNum = NumericUtil.hexToBigInteger(privateKey);
if (NumericUtil.hexToBytes(this.privateKey).length != 32
|| pkNum.compareTo((ECKey.CURVE.getN().subtract(BigInteger.ONE))) >= 0
|| pkNum.compareTo(BigInteger.ONE) <= 0) {
throw new TokenException(Messages.PRIVATE_KEY_INVALID);
}
// validating public key
byte[] pubKeyBytes = ECKey.fromPrivate(pkNum).getPubKey();
BigInteger pubKeyNum = new BigInteger(1, pubKeyBytes);
if (pubKeyNum.compareTo(BigInteger.ZERO) == 0) {
throw new TokenException(Messages.PRIVATE_KEY_INVALID);
}
} catch (Exception ex) {
throw new TokenException(Messages.PRIVATE_KEY_INVALID);
}
return this.privateKey;
}
}
| 1,595 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
BitcoinCashMainNetParams.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/network/BitcoinCashMainNetParams.java | package org.consenlabs.tokencore.wallet.network;
import com.google.common.base.Preconditions;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.Sha256Hash;
import org.bitcoinj.core.Utils;
import org.bitcoinj.net.discovery.HttpDiscovery;
import org.bitcoinj.params.AbstractBitcoinNetParams;
import java.net.URI;
/**
*
* Created by pie on 2020/7/26 22: 57.
*/
public class BitcoinCashMainNetParams extends AbstractBitcoinNetParams {
private static BitcoinCashMainNetParams instance;
private BitcoinCashMainNetParams() {
this.interval = 2016;
this.targetTimespan = 1209600;
this.maxTarget = Utils.decodeCompactBits(486604799L);
this.dumpedPrivateKeyHeader = 128;
this.addressHeader = 0;
this.p2shHeader = 5;
this.acceptableAddressCodes = new int[]{this.addressHeader, this.p2shHeader};
this.port = 8333;
this.packetMagic = 4190024921L;
this.bip32HeaderPub = 76067358;
this.bip32HeaderPriv = 76066276;
this.majorityEnforceBlockUpgrade = 750;
this.majorityRejectBlockOutdated = 950;
this.majorityWindow = 1000;
this.genesisBlock.setDifficultyTarget(486604799L);
this.genesisBlock.setTime(1231006505L);
this.genesisBlock.setNonce(2083236893L);
this.id = "org.bitcoin.production";
this.subsidyDecreaseBlockCount = 210000;
this.spendableCoinbaseDepth = 100;
String genesisHash = this.genesisBlock.getHashAsString();
Preconditions.checkState(genesisHash.equals("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"), genesisHash);
this.checkpoints.put(91722, Sha256Hash.wrap("00000000000271a2dc26e7667f8419f2e15416dc6955e5a6c6cdf3f2574dd08e"));
this.checkpoints.put(91812, Sha256Hash.wrap("00000000000af0aed4792b1acee3d966af36cf5def14935db8de83d6f9306f2f"));
this.checkpoints.put(91842, Sha256Hash.wrap("00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec"));
this.checkpoints.put(91880, Sha256Hash.wrap("00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721"));
this.checkpoints.put(200000, Sha256Hash.wrap("000000000000034a7dedef4a161fa058a2d67a173a90155f3a2fe6fc132e0ebf"));
this.dnsSeeds = new String[]{"seed.bitcoin.sipa.be", "dnsseed.bluematt.me", "dnsseed.bitcoin.dashjr.org", "seed.bitcoinstats.com", "seed.bitnodes.io", "bitseed.xf2.org", "seed.bitcoin.jonasschnelli.ch", "bitcoin.bloqseeds.net"};
this.httpSeeds = new HttpDiscovery.Details[]{new HttpDiscovery.Details(ECKey.fromPublicOnly(Utils.HEX.decode("0238746c59d46d5408bf8b1d0af5740fe1a6e1703fcb56b2953f0b965c740d256f")), URI.create("http://httpseed.bitcoin.schildbach.de/peers"))};
this.addrSeeds = new int[]{500895794, 1648545344, 1389798469, 769107013, -1974219449, 1931884368, -635190697, -321589929, 172026969, 1977409888, 2113365905, -1992881235, -1527638867, 1987510446, 1670054936, -2037772264, -845204690, 19490110, -862790594, -1771628992, 1447591488, 1533473856, -1311760575, -237215679, -1043256510, -2034625981, 1810161475, 1833758531, -779221436, 447787844, 1703191365, -406739899, 1489937477, -975526843, 568173637, 1027298118, 333796167, 276877898, -1906237877, -2125361589, 1820565067, -491976116, -71562676, 2136698444, 1917067854, 318788942, 543753810, 1514714706, 1975895890, 1127599188, 873451860, -2017430443, 142289750, -1978451369, -1406942633, 1882671449, -77343653, -1180604324, 403535452, 1733256285, 80955742, 501500766, 1323869026, 233642851, -1045410963, -1919806079, -1749554558, 486029966, -1857483859, 165442990, -1704101458, -1569883730, 265326510, 255737778, 1335119794, -861648712, 1053649592, -1445616196, -1929307711, 72980437, -905863719, 223505485, -1410221500, 1722919765, 291894370, 1054329773, -1550864786, 1003670445, -747698873, 551516224, 2050193218, 1419742795, -1872611748, -744884894, 726824097, -1897946797, 1006613319, 1886699352, -1219507283, 1532655963, 49949134, 1516714196, -392048066, -275200955, 1259293004, -1564729770, 1989455203, -1532493629, 100509389, -1625155746, 910850395, 1398965717, -1404778028, 184952141, 353120212, 849677772, -42348984, -245564845, 1723866720, 1807902305, -1069856850, 1306139521, 847619265, -2009290387, 903219788, -622815420, 774983009, -2065545265, 1820411218, 974964312, -1730612350, -444282021, 367550551, 2063683662, -665658040, 1446522710, 173929556, -1596879592, 780775752, -1482944180, -874721196, 1428405315, -1451022784, -1979293372, 949273532, -1418281128, 1778485953, -21016765, 791070296, 823144270, -2048316971, 706484062, -60019503, 665865069, -553499056, 370624696, 683566464, 1472095616, 485386106, -1435781310, -1705798069, 173681997, 607438424, -1706471593, 515575368, -166676387, 125751108, 139536572, 1537309208, 667556674, -123729066, -53165481, -818953890, -661135278, 1286447183, 792065749, 942467273, -450652085, 1066690630, 1623768643, 1104831063, -569646782, -1366666165, -269434284, 504330587, -1364031344, -904483623, 508026328, -1936963543, -763508921, -717547933, 1083617635, -1668425384, -887949216, -1636224932, 1086432325, 1251001020, 742016589, 656929340, 816860013, 1493322936, -1601050963, 833637229, -1029880154, 1670598578, -652063298, -1621552936, 2136148587, 1965989013, 1699034440, -1534804410, -832955559, 1896744728, 1184972056, -626044136, -995557549, -2018792878, -1218130095, -1308467894, 1832197697, -1070218434, -1540177566, 1643066542, -781197892, 141617345, 812705985, -1670256447, -1533467805, -2052983197, 1099228505, 416902872, 397990869, 1625804056, -437383092, -1424511902, 511208987, 1562621794, -231174226, -2010709152, -1638187648, 2107971762, -1251919035, 450109246, -716143286, -2045253207, -1839521124, -219601598, 1202652484, 1941284931, -1179148115, 61294800, 175110242, 1721032546, 1006291272, -1911976113, 1953044163, 49516111, 1086001731, 1783943522, 1611153739, -1525450420, 1363845955, 1668814663, -608798373, -318353320, 1121078086, 353925452, -1691937151, 1944387501, 106199119, 1133365573, 1679312550, 756746564, -1800040120, -1925802664, -1515620766, -1955570878, -829291346, -1923595184, 771102037, -289408701, 779483981, 1056504919, -1725885602, -1909390290, -1246778045, -1980961327, -1661157305, -1882386612, -1102449235, 342527301, -1738106184, -1730603170, -777460627, -2087044424, 1084227948, 1831322199, -1753219155, 2074762589, 303283779, -1318591063, 1678764234, -1130453419, 260180556, 252276825, 1772918140, 913146963, -1313200060, -2007502719, 1890958947, -985316021, -1355358511, -1247498158, 569402065, 1923844530, 1956926232, -2095913284, -1189702049, -1968715688, -25231443};
}
public static synchronized BitcoinCashMainNetParams get() {
if (instance == null) {
instance = new BitcoinCashMainNetParams();
}
return instance;
}
@Override
public String getPaymentProtocolId() {
return "main";
}
}
| 6,901 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
LitecoinMainNetParams.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/network/LitecoinMainNetParams.java | package org.consenlabs.tokencore.wallet.network;
import com.google.common.base.Preconditions;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.Sha256Hash;
import org.bitcoinj.core.Utils;
import org.bitcoinj.net.discovery.HttpDiscovery;
import org.bitcoinj.params.AbstractBitcoinNetParams;
import java.net.URI;
public class LitecoinMainNetParams extends AbstractBitcoinNetParams {
public static final int MAINNET_MAJORITY_WINDOW = 1000;
public static final int MAINNET_MAJORITY_REJECT_BLOCK_OUTDATED = 950;
public static final int MAINNET_MAJORITY_ENFORCE_BLOCK_UPGRADE = 750;
public static final int ADDRESS_HEADER_2 = 50;
private static LitecoinMainNetParams instance;
private LitecoinMainNetParams() {
this.interval = 2016;
this.targetTimespan = 1209600;
this.maxTarget = Utils.decodeCompactBits(486604799L);
this.dumpedPrivateKeyHeader = 176;
this.addressHeader = 48;
this.p2shHeader = 5;
this.acceptableAddressCodes = new int[]{this.addressHeader, this.p2shHeader, ADDRESS_HEADER_2};
this.port = 8333;
this.packetMagic = 4190024921L;
this.bip32HeaderPub = 76067358;
this.bip32HeaderPriv = 76066276;
this.majorityEnforceBlockUpgrade = 750;
this.majorityRejectBlockOutdated = 950;
this.majorityWindow = 1000;
this.genesisBlock.setDifficultyTarget(486604799L);
this.genesisBlock.setTime(1231006505L);
this.genesisBlock.setNonce(2083236893L);
this.id = "org.bitcoin.production";
this.subsidyDecreaseBlockCount = 210000;
this.spendableCoinbaseDepth = 100;
String genesisHash = this.genesisBlock.getHashAsString();
Preconditions.checkState(genesisHash.equals("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"), genesisHash);
this.checkpoints.put(91722, Sha256Hash.wrap("00000000000271a2dc26e7667f8419f2e15416dc6955e5a6c6cdf3f2574dd08e"));
this.checkpoints.put(91812, Sha256Hash.wrap("00000000000af0aed4792b1acee3d966af36cf5def14935db8de83d6f9306f2f"));
this.checkpoints.put(91842, Sha256Hash.wrap("00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec"));
this.checkpoints.put(91880, Sha256Hash.wrap("00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721"));
this.checkpoints.put(200000, Sha256Hash.wrap("000000000000034a7dedef4a161fa058a2d67a173a90155f3a2fe6fc132e0ebf"));
this.dnsSeeds = new String[]{"seed.bitcoin.sipa.be", "dnsseed.bluematt.me", "dnsseed.bitcoin.dashjr.org", "seed.bitcoinstats.com", "seed.bitnodes.io", "bitseed.xf2.org", "seed.bitcoin.jonasschnelli.ch", "bitcoin.bloqseeds.net"};
this.httpSeeds = new HttpDiscovery.Details[]{new HttpDiscovery.Details(ECKey.fromPublicOnly(Utils.HEX.decode("0238746c59d46d5408bf8b1d0af5740fe1a6e1703fcb56b2953f0b965c740d256f")), URI.create("http://httpseed.bitcoin.schildbach.de/peers"))};
this.addrSeeds = new int[]{500895794, 1648545344, 1389798469, 769107013, -1974219449, 1931884368, -635190697, -321589929, 172026969, 1977409888, 2113365905, -1992881235, -1527638867, 1987510446, 1670054936, -2037772264, -845204690, 19490110, -862790594, -1771628992, 1447591488, 1533473856, -1311760575, -237215679, -1043256510, -2034625981, 1810161475, 1833758531, -779221436, 447787844, 1703191365, -406739899, 1489937477, -975526843, 568173637, 1027298118, 333796167, 276877898, -1906237877, -2125361589, 1820565067, -491976116, -71562676, 2136698444, 1917067854, 318788942, 543753810, 1514714706, 1975895890, 1127599188, 873451860, -2017430443, 142289750, -1978451369, -1406942633, 1882671449, -77343653, -1180604324, 403535452, 1733256285, 80955742, 501500766, 1323869026, 233642851, -1045410963, -1919806079, -1749554558, 486029966, -1857483859, 165442990, -1704101458, -1569883730, 265326510, 255737778, 1335119794, -861648712, 1053649592, -1445616196, -1929307711, 72980437, -905863719, 223505485, -1410221500, 1722919765, 291894370, 1054329773, -1550864786, 1003670445, -747698873, 551516224, 2050193218, 1419742795, -1872611748, -744884894, 726824097, -1897946797, 1006613319, 1886699352, -1219507283, 1532655963, 49949134, 1516714196, -392048066, -275200955, 1259293004, -1564729770, 1989455203, -1532493629, 100509389, -1625155746, 910850395, 1398965717, -1404778028, 184952141, 353120212, 849677772, -42348984, -245564845, 1723866720, 1807902305, -1069856850, 1306139521, 847619265, -2009290387, 903219788, -622815420, 774983009, -2065545265, 1820411218, 974964312, -1730612350, -444282021, 367550551, 2063683662, -665658040, 1446522710, 173929556, -1596879592, 780775752, -1482944180, -874721196, 1428405315, -1451022784, -1979293372, 949273532, -1418281128, 1778485953, -21016765, 791070296, 823144270, -2048316971, 706484062, -60019503, 665865069, -553499056, 370624696, 683566464, 1472095616, 485386106, -1435781310, -1705798069, 173681997, 607438424, -1706471593, 515575368, -166676387, 125751108, 139536572, 1537309208, 667556674, -123729066, -53165481, -818953890, -661135278, 1286447183, 792065749, 942467273, -450652085, 1066690630, 1623768643, 1104831063, -569646782, -1366666165, -269434284, 504330587, -1364031344, -904483623, 508026328, -1936963543, -763508921, -717547933, 1083617635, -1668425384, -887949216, -1636224932, 1086432325, 1251001020, 742016589, 656929340, 816860013, 1493322936, -1601050963, 833637229, -1029880154, 1670598578, -652063298, -1621552936, 2136148587, 1965989013, 1699034440, -1534804410, -832955559, 1896744728, 1184972056, -626044136, -995557549, -2018792878, -1218130095, -1308467894, 1832197697, -1070218434, -1540177566, 1643066542, -781197892, 141617345, 812705985, -1670256447, -1533467805, -2052983197, 1099228505, 416902872, 397990869, 1625804056, -437383092, -1424511902, 511208987, 1562621794, -231174226, -2010709152, -1638187648, 2107971762, -1251919035, 450109246, -716143286, -2045253207, -1839521124, -219601598, 1202652484, 1941284931, -1179148115, 61294800, 175110242, 1721032546, 1006291272, -1911976113, 1953044163, 49516111, 1086001731, 1783943522, 1611153739, -1525450420, 1363845955, 1668814663, -608798373, -318353320, 1121078086, 353925452, -1691937151, 1944387501, 106199119, 1133365573, 1679312550, 756746564, -1800040120, -1925802664, -1515620766, -1955570878, -829291346, -1923595184, 771102037, -289408701, 779483981, 1056504919, -1725885602, -1909390290, -1246778045, -1980961327, -1661157305, -1882386612, -1102449235, 342527301, -1738106184, -1730603170, -777460627, -2087044424, 1084227948, 1831322199, -1753219155, 2074762589, 303283779, -1318591063, 1678764234, -1130453419, 260180556, 252276825, 1772918140, 913146963, -1313200060, -2007502719, 1890958947, -985316021, -1355358511, -1247498158, 569402065, 1923844530, 1956926232, -2095913284, -1189702049, -1968715688, -25231443};
}
public static synchronized LitecoinMainNetParams get() {
if (instance == null) {
instance = new LitecoinMainNetParams();
}
return instance;
}
public String getPaymentProtocolId() {
return "main";
}
}
| 7,163 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
BitcoinSvMainNetParams.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/network/BitcoinSvMainNetParams.java | package org.consenlabs.tokencore.wallet.network;
import com.google.common.base.Preconditions;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.Sha256Hash;
import org.bitcoinj.core.Utils;
import org.bitcoinj.net.discovery.HttpDiscovery;
import org.bitcoinj.params.AbstractBitcoinNetParams;
import java.net.URI;
/**
*
* Created by pie on 2020/7/26 22: 58.
*/
public class BitcoinSvMainNetParams extends AbstractBitcoinNetParams {
private static BitcoinSvMainNetParams instance;
private BitcoinSvMainNetParams() {
this.interval = 2016;
this.targetTimespan = 1209600;
this.maxTarget = Utils.decodeCompactBits(486604799L);
this.dumpedPrivateKeyHeader = 128;
this.addressHeader = 0;
this.p2shHeader = 5;
this.acceptableAddressCodes = new int[]{this.addressHeader, this.p2shHeader};
this.port = 8333;
this.packetMagic = 4190024921L;
this.bip32HeaderPub = 76067358;
this.bip32HeaderPriv = 76066276;
this.majorityEnforceBlockUpgrade = 750;
this.majorityRejectBlockOutdated = 950;
this.majorityWindow = 1000;
this.genesisBlock.setDifficultyTarget(486604799L);
this.genesisBlock.setTime(1231006505L);
this.genesisBlock.setNonce(2083236893L);
this.id = "org.bitcoin.production";
this.subsidyDecreaseBlockCount = 210000;
this.spendableCoinbaseDepth = 100;
String genesisHash = this.genesisBlock.getHashAsString();
Preconditions.checkState(genesisHash.equals("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"), genesisHash);
this.checkpoints.put(91722, Sha256Hash.wrap("00000000000271a2dc26e7667f8419f2e15416dc6955e5a6c6cdf3f2574dd08e"));
this.checkpoints.put(91812, Sha256Hash.wrap("00000000000af0aed4792b1acee3d966af36cf5def14935db8de83d6f9306f2f"));
this.checkpoints.put(91842, Sha256Hash.wrap("00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec"));
this.checkpoints.put(91880, Sha256Hash.wrap("00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721"));
this.checkpoints.put(200000, Sha256Hash.wrap("000000000000034a7dedef4a161fa058a2d67a173a90155f3a2fe6fc132e0ebf"));
this.dnsSeeds = new String[]{"seed.bitcoin.sipa.be", "dnsseed.bluematt.me", "dnsseed.bitcoin.dashjr.org", "seed.bitcoinstats.com", "seed.bitnodes.io", "bitseed.xf2.org", "seed.bitcoin.jonasschnelli.ch", "bitcoin.bloqseeds.net"};
this.httpSeeds = new HttpDiscovery.Details[]{new HttpDiscovery.Details(ECKey.fromPublicOnly(Utils.HEX.decode("0238746c59d46d5408bf8b1d0af5740fe1a6e1703fcb56b2953f0b965c740d256f")), URI.create("http://httpseed.bitcoin.schildbach.de/peers"))};
this.addrSeeds = new int[]{500895794, 1648545344, 1389798469, 769107013, -1974219449, 1931884368, -635190697, -321589929, 172026969, 1977409888, 2113365905, -1992881235, -1527638867, 1987510446, 1670054936, -2037772264, -845204690, 19490110, -862790594, -1771628992, 1447591488, 1533473856, -1311760575, -237215679, -1043256510, -2034625981, 1810161475, 1833758531, -779221436, 447787844, 1703191365, -406739899, 1489937477, -975526843, 568173637, 1027298118, 333796167, 276877898, -1906237877, -2125361589, 1820565067, -491976116, -71562676, 2136698444, 1917067854, 318788942, 543753810, 1514714706, 1975895890, 1127599188, 873451860, -2017430443, 142289750, -1978451369, -1406942633, 1882671449, -77343653, -1180604324, 403535452, 1733256285, 80955742, 501500766, 1323869026, 233642851, -1045410963, -1919806079, -1749554558, 486029966, -1857483859, 165442990, -1704101458, -1569883730, 265326510, 255737778, 1335119794, -861648712, 1053649592, -1445616196, -1929307711, 72980437, -905863719, 223505485, -1410221500, 1722919765, 291894370, 1054329773, -1550864786, 1003670445, -747698873, 551516224, 2050193218, 1419742795, -1872611748, -744884894, 726824097, -1897946797, 1006613319, 1886699352, -1219507283, 1532655963, 49949134, 1516714196, -392048066, -275200955, 1259293004, -1564729770, 1989455203, -1532493629, 100509389, -1625155746, 910850395, 1398965717, -1404778028, 184952141, 353120212, 849677772, -42348984, -245564845, 1723866720, 1807902305, -1069856850, 1306139521, 847619265, -2009290387, 903219788, -622815420, 774983009, -2065545265, 1820411218, 974964312, -1730612350, -444282021, 367550551, 2063683662, -665658040, 1446522710, 173929556, -1596879592, 780775752, -1482944180, -874721196, 1428405315, -1451022784, -1979293372, 949273532, -1418281128, 1778485953, -21016765, 791070296, 823144270, -2048316971, 706484062, -60019503, 665865069, -553499056, 370624696, 683566464, 1472095616, 485386106, -1435781310, -1705798069, 173681997, 607438424, -1706471593, 515575368, -166676387, 125751108, 139536572, 1537309208, 667556674, -123729066, -53165481, -818953890, -661135278, 1286447183, 792065749, 942467273, -450652085, 1066690630, 1623768643, 1104831063, -569646782, -1366666165, -269434284, 504330587, -1364031344, -904483623, 508026328, -1936963543, -763508921, -717547933, 1083617635, -1668425384, -887949216, -1636224932, 1086432325, 1251001020, 742016589, 656929340, 816860013, 1493322936, -1601050963, 833637229, -1029880154, 1670598578, -652063298, -1621552936, 2136148587, 1965989013, 1699034440, -1534804410, -832955559, 1896744728, 1184972056, -626044136, -995557549, -2018792878, -1218130095, -1308467894, 1832197697, -1070218434, -1540177566, 1643066542, -781197892, 141617345, 812705985, -1670256447, -1533467805, -2052983197, 1099228505, 416902872, 397990869, 1625804056, -437383092, -1424511902, 511208987, 1562621794, -231174226, -2010709152, -1638187648, 2107971762, -1251919035, 450109246, -716143286, -2045253207, -1839521124, -219601598, 1202652484, 1941284931, -1179148115, 61294800, 175110242, 1721032546, 1006291272, -1911976113, 1953044163, 49516111, 1086001731, 1783943522, 1611153739, -1525450420, 1363845955, 1668814663, -608798373, -318353320, 1121078086, 353925452, -1691937151, 1944387501, 106199119, 1133365573, 1679312550, 756746564, -1800040120, -1925802664, -1515620766, -1955570878, -829291346, -1923595184, 771102037, -289408701, 779483981, 1056504919, -1725885602, -1909390290, -1246778045, -1980961327, -1661157305, -1882386612, -1102449235, 342527301, -1738106184, -1730603170, -777460627, -2087044424, 1084227948, 1831322199, -1753219155, 2074762589, 303283779, -1318591063, 1678764234, -1130453419, 260180556, 252276825, 1772918140, 913146963, -1313200060, -2007502719, 1890958947, -985316021, -1355358511, -1247498158, 569402065, 1923844530, 1956926232, -2095913284, -1189702049, -1968715688, -25231443};
}
public static synchronized BitcoinSvMainNetParams get() {
if (instance == null) {
instance = new BitcoinSvMainNetParams();
}
return instance;
}
@Override
public String getPaymentProtocolId() {
return "main";
}
}
| 6,890 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
DogecoinMainNetParams.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/network/DogecoinMainNetParams.java | package org.consenlabs.tokencore.wallet.network;
import com.google.common.base.Preconditions;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.Sha256Hash;
import org.bitcoinj.core.Utils;
import org.bitcoinj.net.discovery.HttpDiscovery;
import org.bitcoinj.params.AbstractBitcoinNetParams;
import java.net.URI;
/**
*
* Created by pie on 2020/7/26 23: 02.
*/
public class DogecoinMainNetParams extends AbstractBitcoinNetParams {
private static DogecoinMainNetParams instance;
private DogecoinMainNetParams() {
this.interval = 2016;
this.targetTimespan = 1209600;
this.maxTarget = Utils.decodeCompactBits(486604799L);
this.dumpedPrivateKeyHeader = 158;
this.addressHeader = 30;
this.p2shHeader = 22;
this.acceptableAddressCodes = new int[]{this.addressHeader, this.p2shHeader};
this.port = 8333;
this.packetMagic = 4190024921L;
this.bip32HeaderPub = 76067358;
this.bip32HeaderPriv = 76066276;
this.majorityEnforceBlockUpgrade = 750;
this.majorityRejectBlockOutdated = 950;
this.majorityWindow = 1000;
this.genesisBlock.setDifficultyTarget(486604799L);
this.genesisBlock.setTime(1231006505L);
this.genesisBlock.setNonce(2083236893L);
this.id = "org.bitcoin.production";
this.subsidyDecreaseBlockCount = 210000;
this.spendableCoinbaseDepth = 100;
String genesisHash = this.genesisBlock.getHashAsString();
Preconditions.checkState(genesisHash.equals("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"), genesisHash);
this.checkpoints.put(91722, Sha256Hash.wrap("00000000000271a2dc26e7667f8419f2e15416dc6955e5a6c6cdf3f2574dd08e"));
this.checkpoints.put(91812, Sha256Hash.wrap("00000000000af0aed4792b1acee3d966af36cf5def14935db8de83d6f9306f2f"));
this.checkpoints.put(91842, Sha256Hash.wrap("00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec"));
this.checkpoints.put(91880, Sha256Hash.wrap("00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721"));
this.checkpoints.put(200000, Sha256Hash.wrap("000000000000034a7dedef4a161fa058a2d67a173a90155f3a2fe6fc132e0ebf"));
this.dnsSeeds = new String[]{"seed.bitcoin.sipa.be", "dnsseed.bluematt.me", "dnsseed.bitcoin.dashjr.org", "seed.bitcoinstats.com", "seed.bitnodes.io", "bitseed.xf2.org", "seed.bitcoin.jonasschnelli.ch", "bitcoin.bloqseeds.net"};
this.httpSeeds = new HttpDiscovery.Details[]{new HttpDiscovery.Details(ECKey.fromPublicOnly(Utils.HEX.decode("0238746c59d46d5408bf8b1d0af5740fe1a6e1703fcb56b2953f0b965c740d256f")), URI.create("http://httpseed.bitcoin.schildbach.de/peers"))};
this.addrSeeds = new int[]{500895794, 1648545344, 1389798469, 769107013, -1974219449, 1931884368, -635190697, -321589929, 172026969, 1977409888, 2113365905, -1992881235, -1527638867, 1987510446, 1670054936, -2037772264, -845204690, 19490110, -862790594, -1771628992, 1447591488, 1533473856, -1311760575, -237215679, -1043256510, -2034625981, 1810161475, 1833758531, -779221436, 447787844, 1703191365, -406739899, 1489937477, -975526843, 568173637, 1027298118, 333796167, 276877898, -1906237877, -2125361589, 1820565067, -491976116, -71562676, 2136698444, 1917067854, 318788942, 543753810, 1514714706, 1975895890, 1127599188, 873451860, -2017430443, 142289750, -1978451369, -1406942633, 1882671449, -77343653, -1180604324, 403535452, 1733256285, 80955742, 501500766, 1323869026, 233642851, -1045410963, -1919806079, -1749554558, 486029966, -1857483859, 165442990, -1704101458, -1569883730, 265326510, 255737778, 1335119794, -861648712, 1053649592, -1445616196, -1929307711, 72980437, -905863719, 223505485, -1410221500, 1722919765, 291894370, 1054329773, -1550864786, 1003670445, -747698873, 551516224, 2050193218, 1419742795, -1872611748, -744884894, 726824097, -1897946797, 1006613319, 1886699352, -1219507283, 1532655963, 49949134, 1516714196, -392048066, -275200955, 1259293004, -1564729770, 1989455203, -1532493629, 100509389, -1625155746, 910850395, 1398965717, -1404778028, 184952141, 353120212, 849677772, -42348984, -245564845, 1723866720, 1807902305, -1069856850, 1306139521, 847619265, -2009290387, 903219788, -622815420, 774983009, -2065545265, 1820411218, 974964312, -1730612350, -444282021, 367550551, 2063683662, -665658040, 1446522710, 173929556, -1596879592, 780775752, -1482944180, -874721196, 1428405315, -1451022784, -1979293372, 949273532, -1418281128, 1778485953, -21016765, 791070296, 823144270, -2048316971, 706484062, -60019503, 665865069, -553499056, 370624696, 683566464, 1472095616, 485386106, -1435781310, -1705798069, 173681997, 607438424, -1706471593, 515575368, -166676387, 125751108, 139536572, 1537309208, 667556674, -123729066, -53165481, -818953890, -661135278, 1286447183, 792065749, 942467273, -450652085, 1066690630, 1623768643, 1104831063, -569646782, -1366666165, -269434284, 504330587, -1364031344, -904483623, 508026328, -1936963543, -763508921, -717547933, 1083617635, -1668425384, -887949216, -1636224932, 1086432325, 1251001020, 742016589, 656929340, 816860013, 1493322936, -1601050963, 833637229, -1029880154, 1670598578, -652063298, -1621552936, 2136148587, 1965989013, 1699034440, -1534804410, -832955559, 1896744728, 1184972056, -626044136, -995557549, -2018792878, -1218130095, -1308467894, 1832197697, -1070218434, -1540177566, 1643066542, -781197892, 141617345, 812705985, -1670256447, -1533467805, -2052983197, 1099228505, 416902872, 397990869, 1625804056, -437383092, -1424511902, 511208987, 1562621794, -231174226, -2010709152, -1638187648, 2107971762, -1251919035, 450109246, -716143286, -2045253207, -1839521124, -219601598, 1202652484, 1941284931, -1179148115, 61294800, 175110242, 1721032546, 1006291272, -1911976113, 1953044163, 49516111, 1086001731, 1783943522, 1611153739, -1525450420, 1363845955, 1668814663, -608798373, -318353320, 1121078086, 353925452, -1691937151, 1944387501, 106199119, 1133365573, 1679312550, 756746564, -1800040120, -1925802664, -1515620766, -1955570878, -829291346, -1923595184, 771102037, -289408701, 779483981, 1056504919, -1725885602, -1909390290, -1246778045, -1980961327, -1661157305, -1882386612, -1102449235, 342527301, -1738106184, -1730603170, -777460627, -2087044424, 1084227948, 1831322199, -1753219155, 2074762589, 303283779, -1318591063, 1678764234, -1130453419, 260180556, 252276825, 1772918140, 913146963, -1313200060, -2007502719, 1890958947, -985316021, -1355358511, -1247498158, 569402065, 1923844530, 1956926232, -2095913284, -1189702049, -1968715688, -25231443};
}
public static synchronized DogecoinMainNetParams get() {
if (instance == null) {
instance = new DogecoinMainNetParams();
}
return instance;
}
@Override
public String getPaymentProtocolId() {
return "main";
}
}
| 6,887 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
DashMainNetParams.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/network/DashMainNetParams.java | package org.consenlabs.tokencore.wallet.network;
import com.google.common.base.Preconditions;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.Sha256Hash;
import org.bitcoinj.core.Utils;
import org.bitcoinj.net.discovery.HttpDiscovery;
import org.bitcoinj.params.AbstractBitcoinNetParams;
import java.net.URI;
/**
* Created by pie on 2019-04-25 10: 40.
*/
public class DashMainNetParams extends AbstractBitcoinNetParams {
private static DashMainNetParams instance;
private DashMainNetParams() {
this.interval = 2016;
this.targetTimespan = 1209600;
this.maxTarget = Utils.decodeCompactBits(486604799L);
this.dumpedPrivateKeyHeader = 204;
this.addressHeader = 76;
this.p2shHeader = 16;
this.acceptableAddressCodes = new int[]{this.addressHeader, this.p2shHeader};
this.port = 8333;
this.packetMagic = 4190024921L;
this.bip32HeaderPub = 76067358;
this.bip32HeaderPriv = 76066276;
this.majorityEnforceBlockUpgrade = 750;
this.majorityRejectBlockOutdated = 950;
this.majorityWindow = 1000;
this.genesisBlock.setDifficultyTarget(486604799L);
this.genesisBlock.setTime(1231006505L);
this.genesisBlock.setNonce(2083236893L);
this.id = "org.bitcoin.production";
this.subsidyDecreaseBlockCount = 210000;
this.spendableCoinbaseDepth = 100;
String genesisHash = this.genesisBlock.getHashAsString();
Preconditions.checkState(genesisHash.equals("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"), genesisHash);
this.checkpoints.put(91722, Sha256Hash.wrap("00000000000271a2dc26e7667f8419f2e15416dc6955e5a6c6cdf3f2574dd08e"));
this.checkpoints.put(91812, Sha256Hash.wrap("00000000000af0aed4792b1acee3d966af36cf5def14935db8de83d6f9306f2f"));
this.checkpoints.put(91842, Sha256Hash.wrap("00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec"));
this.checkpoints.put(91880, Sha256Hash.wrap("00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721"));
this.checkpoints.put(200000, Sha256Hash.wrap("000000000000034a7dedef4a161fa058a2d67a173a90155f3a2fe6fc132e0ebf"));
this.dnsSeeds = new String[]{"seed.bitcoin.sipa.be", "dnsseed.bluematt.me", "dnsseed.bitcoin.dashjr.org", "seed.bitcoinstats.com", "seed.bitnodes.io", "bitseed.xf2.org", "seed.bitcoin.jonasschnelli.ch", "bitcoin.bloqseeds.net"};
this.httpSeeds = new HttpDiscovery.Details[]{new HttpDiscovery.Details(ECKey.fromPublicOnly(Utils.HEX.decode("0238746c59d46d5408bf8b1d0af5740fe1a6e1703fcb56b2953f0b965c740d256f")), URI.create("http://httpseed.bitcoin.schildbach.de/peers"))};
this.addrSeeds = new int[]{500895794, 1648545344, 1389798469, 769107013, -1974219449, 1931884368, -635190697, -321589929, 172026969, 1977409888, 2113365905, -1992881235, -1527638867, 1987510446, 1670054936, -2037772264, -845204690, 19490110, -862790594, -1771628992, 1447591488, 1533473856, -1311760575, -237215679, -1043256510, -2034625981, 1810161475, 1833758531, -779221436, 447787844, 1703191365, -406739899, 1489937477, -975526843, 568173637, 1027298118, 333796167, 276877898, -1906237877, -2125361589, 1820565067, -491976116, -71562676, 2136698444, 1917067854, 318788942, 543753810, 1514714706, 1975895890, 1127599188, 873451860, -2017430443, 142289750, -1978451369, -1406942633, 1882671449, -77343653, -1180604324, 403535452, 1733256285, 80955742, 501500766, 1323869026, 233642851, -1045410963, -1919806079, -1749554558, 486029966, -1857483859, 165442990, -1704101458, -1569883730, 265326510, 255737778, 1335119794, -861648712, 1053649592, -1445616196, -1929307711, 72980437, -905863719, 223505485, -1410221500, 1722919765, 291894370, 1054329773, -1550864786, 1003670445, -747698873, 551516224, 2050193218, 1419742795, -1872611748, -744884894, 726824097, -1897946797, 1006613319, 1886699352, -1219507283, 1532655963, 49949134, 1516714196, -392048066, -275200955, 1259293004, -1564729770, 1989455203, -1532493629, 100509389, -1625155746, 910850395, 1398965717, -1404778028, 184952141, 353120212, 849677772, -42348984, -245564845, 1723866720, 1807902305, -1069856850, 1306139521, 847619265, -2009290387, 903219788, -622815420, 774983009, -2065545265, 1820411218, 974964312, -1730612350, -444282021, 367550551, 2063683662, -665658040, 1446522710, 173929556, -1596879592, 780775752, -1482944180, -874721196, 1428405315, -1451022784, -1979293372, 949273532, -1418281128, 1778485953, -21016765, 791070296, 823144270, -2048316971, 706484062, -60019503, 665865069, -553499056, 370624696, 683566464, 1472095616, 485386106, -1435781310, -1705798069, 173681997, 607438424, -1706471593, 515575368, -166676387, 125751108, 139536572, 1537309208, 667556674, -123729066, -53165481, -818953890, -661135278, 1286447183, 792065749, 942467273, -450652085, 1066690630, 1623768643, 1104831063, -569646782, -1366666165, -269434284, 504330587, -1364031344, -904483623, 508026328, -1936963543, -763508921, -717547933, 1083617635, -1668425384, -887949216, -1636224932, 1086432325, 1251001020, 742016589, 656929340, 816860013, 1493322936, -1601050963, 833637229, -1029880154, 1670598578, -652063298, -1621552936, 2136148587, 1965989013, 1699034440, -1534804410, -832955559, 1896744728, 1184972056, -626044136, -995557549, -2018792878, -1218130095, -1308467894, 1832197697, -1070218434, -1540177566, 1643066542, -781197892, 141617345, 812705985, -1670256447, -1533467805, -2052983197, 1099228505, 416902872, 397990869, 1625804056, -437383092, -1424511902, 511208987, 1562621794, -231174226, -2010709152, -1638187648, 2107971762, -1251919035, 450109246, -716143286, -2045253207, -1839521124, -219601598, 1202652484, 1941284931, -1179148115, 61294800, 175110242, 1721032546, 1006291272, -1911976113, 1953044163, 49516111, 1086001731, 1783943522, 1611153739, -1525450420, 1363845955, 1668814663, -608798373, -318353320, 1121078086, 353925452, -1691937151, 1944387501, 106199119, 1133365573, 1679312550, 756746564, -1800040120, -1925802664, -1515620766, -1955570878, -829291346, -1923595184, 771102037, -289408701, 779483981, 1056504919, -1725885602, -1909390290, -1246778045, -1980961327, -1661157305, -1882386612, -1102449235, 342527301, -1738106184, -1730603170, -777460627, -2087044424, 1084227948, 1831322199, -1753219155, 2074762589, 303283779, -1318591063, 1678764234, -1130453419, 260180556, 252276825, 1772918140, 913146963, -1313200060, -2007502719, 1890958947, -985316021, -1355358511, -1247498158, 569402065, 1923844530, 1956926232, -2095913284, -1189702049, -1968715688, -25231443};
}
public static synchronized DashMainNetParams get() {
if (instance == null) {
instance = new DashMainNetParams();
}
return instance;
}
@Override
public String getPaymentProtocolId() {
return "main";
}
}
| 6,866 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
AddressCreator.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/address/AddressCreator.java | package org.consenlabs.tokencore.wallet.address;
public interface AddressCreator {
String fromPrivateKey(String prvKeyHex);
String fromPrivateKey(byte[] prvKeyBytes);
}
| 184 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
BitcoinAddressCreator.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/address/BitcoinAddressCreator.java | package org.consenlabs.tokencore.wallet.address;
import org.bitcoinj.core.DumpedPrivateKey;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.NetworkParameters;
import org.consenlabs.tokencore.foundation.utils.NumericUtil;
public class BitcoinAddressCreator implements AddressCreator {
private NetworkParameters networkParameters;
public BitcoinAddressCreator(NetworkParameters networkParameters) {
this.networkParameters = networkParameters;
}
@Override
public String fromPrivateKey(String prvKeyHex) {
ECKey key;
if (prvKeyHex.length() == 51 || prvKeyHex.length() == 52) {
DumpedPrivateKey dumpedPrivateKey = DumpedPrivateKey.fromBase58(networkParameters, prvKeyHex);
key = dumpedPrivateKey.getKey();
} else {
key = ECKey.fromPrivate(NumericUtil.hexToBytes(prvKeyHex));
}
return key.toAddress(this.networkParameters).toBase58();
}
@Override
public String fromPrivateKey(byte[] prvKeyBytes) {
ECKey key = ECKey.fromPrivate(prvKeyBytes);
return key.toAddress(this.networkParameters).toBase58();
}
}
| 1,113 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
SegWitBitcoinAddressCreator.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/address/SegWitBitcoinAddressCreator.java | package org.consenlabs.tokencore.wallet.address;
import org.bitcoinj.core.*;
import org.consenlabs.tokencore.foundation.utils.NumericUtil;
import org.consenlabs.tokencore.wallet.model.Messages;
import org.consenlabs.tokencore.wallet.model.TokenException;
public class SegWitBitcoinAddressCreator implements AddressCreator {
private NetworkParameters networkParameters;
public SegWitBitcoinAddressCreator(NetworkParameters networkParameters) {
this.networkParameters = networkParameters;
}
@Override
public String fromPrivateKey(String prvKeyHex) {
ECKey key;
if (prvKeyHex.length() == 51 || prvKeyHex.length() == 52) {
DumpedPrivateKey dumpedPrivateKey = DumpedPrivateKey.fromBase58(networkParameters, prvKeyHex);
key = dumpedPrivateKey.getKey();
if (!key.isCompressed()) {
throw new TokenException(Messages.SEGWIT_NEEDS_COMPRESS_PUBLIC_KEY);
}
} else {
key = ECKey.fromPrivate(NumericUtil.hexToBytes(prvKeyHex), true);
}
return calcSegWitAddress(key.getPubKeyHash());
}
@Override
public String fromPrivateKey(byte[] prvKeyBytes) {
ECKey key = ECKey.fromPrivate(prvKeyBytes, true);
return calcSegWitAddress(key.getPubKeyHash());
}
private String calcSegWitAddress(byte[] pubKeyHash) {
String redeemScript = String.format("0x0014%s", NumericUtil.bytesToHex(pubKeyHash));
return Address.fromP2SHHash(networkParameters, Utils.sha256hash160(NumericUtil.hexToBytes(redeemScript))).toBase58();
}
public Address fromPrivateKey(ECKey ecKey) {
String redeemScript = String.format("0x0014%s", NumericUtil.bytesToHex(ecKey.getPubKeyHash()));
return Address.fromP2SHHash(networkParameters, Utils.sha256hash160(NumericUtil.hexToBytes(redeemScript)));
}
}
| 1,808 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
AddressCreatorManager.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/address/AddressCreatorManager.java | package org.consenlabs.tokencore.wallet.address;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.params.TestNet3Params;
import org.consenlabs.tokencore.wallet.model.ChainType;
import org.consenlabs.tokencore.wallet.model.Messages;
import org.consenlabs.tokencore.wallet.model.Metadata;
import org.consenlabs.tokencore.wallet.model.TokenException;
import org.consenlabs.tokencore.wallet.network.*;
public class AddressCreatorManager {
public static AddressCreator getInstance(String type, boolean isMainnet, String segWit) {
if (ChainType.ETHEREUM.equals(type)) {
return new EthereumAddressCreator();
}else if (ChainType.FILECOIN.equals(type)) {
return new FilecoinAddressCreator();
} else if (ChainType.TRON.equals(type)) {
return new TronAddressCreator();
} else if (ChainType.LITECOIN.equals(type)) {
NetworkParameters network = LitecoinMainNetParams.get();
return new BitcoinAddressCreator(network);
} else if (ChainType.DASH.equals(type)) {
NetworkParameters network = DashMainNetParams.get();
return new BitcoinAddressCreator(network);
} else if (ChainType.DOGECOIN.equals(type)) {
NetworkParameters network = DogecoinMainNetParams.get();
return new BitcoinAddressCreator(network);
} else if (ChainType.BITCOINSV.equals(type)) {
NetworkParameters network = BitcoinSvMainNetParams.get();
return new BitcoinAddressCreator(network);
} else if (ChainType.BITCOINCASH.equals(type)) {
NetworkParameters network = BitcoinCashMainNetParams.get();
return new BitcoinAddressCreator(network);
} else if (ChainType.BITCOIN.equals(type)) {
NetworkParameters network = isMainnet ? MainNetParams.get() : TestNet3Params.get();
if (Metadata.P2WPKH.equals(segWit)) {
return new SegWitBitcoinAddressCreator(network);
}
return new BitcoinAddressCreator(network);
} else {
throw new TokenException(Messages.WALLET_INVALID_TYPE);
}
}
}
| 2,256 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
TronAddressCreator.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/address/TronAddressCreator.java | package org.consenlabs.tokencore.wallet.address;
import org.bitcoinj.core.Base58;
import org.bitcoinj.core.ECKey;
import org.consenlabs.tokencore.foundation.crypto.Hash;
import org.consenlabs.tokencore.foundation.utils.NumericUtil;
import java.math.BigInteger;
import java.util.Arrays;
import static java.util.Arrays.copyOfRange;
/**
* Created by pie on 2020/9/6 22: 28.
*/
public class TronAddressCreator implements AddressCreator {
private static final byte ADD_PRE_FIX_BYTE_MAINNET = (byte) 0x41;
private static final int PUBLIC_KEY_SIZE = 64;
private String encode58Check(byte[] input) {
byte[] hash0 = Hash.sha256(input);
byte[] hash1 = Hash.sha256(hash0);
byte[] inputCheck = new byte[input.length + 4];
System.arraycopy(input, 0, inputCheck, 0, input.length);
System.arraycopy(hash1, 0, inputCheck, input.length, 4);
return Base58.encode(inputCheck);
}
public String fromPublicKey(BigInteger publicKey) {
byte[] pubKeyBytes = NumericUtil.bigIntegerToBytesWithZeroPadded(publicKey, PUBLIC_KEY_SIZE);
return publicKeyToAddress(pubKeyBytes);
}
private String publicKeyToAddress(byte[] pubKeyBytes) {
byte[] hashedBytes = Hash.keccak256(pubKeyBytes);
byte[] address = copyOfRange(hashedBytes, 11, hashedBytes.length);
address[0] = ADD_PRE_FIX_BYTE_MAINNET;
return encode58Check(address);
}
@Override
public String fromPrivateKey(String prvKeyHex) {
ECKey key = ECKey.fromPrivate(NumericUtil.hexToBytes(prvKeyHex), false);
return fromECKey(key);
}
@Override
public String fromPrivateKey(byte[] prvKeyBytes) {
ECKey key = ECKey.fromPrivate(prvKeyBytes, false);
return fromECKey(key);
}
private String fromECKey(ECKey key) {
byte[] pubKeyBytes = key.getPubKey();
return publicKeyToAddress(Arrays.copyOfRange(pubKeyBytes, 1, pubKeyBytes.length));
}
}
| 1,973 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
FilecoinAddressCreator.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/address/FilecoinAddressCreator.java | package org.consenlabs.tokencore.wallet.address;
import cn.hutool.core.codec.Base32;
import cn.hutool.core.util.HexUtil;
import com.filecoinj.crypto.ECKey;
import org.consenlabs.tokencore.foundation.utils.NumericUtil;
import ove.crypto.digest.Blake2b;
import java.util.Arrays;
public class FilecoinAddressCreator implements AddressCreator{
private String publicKeyToAddress(byte[] pubKeyBytes) {
Blake2b.Digest digest = Blake2b.Digest.newInstance(20);
String hash = HexUtil.encodeHexStr(digest.digest(pubKeyBytes));
String pubKeyHash = "01" + HexUtil.encodeHexStr(digest.digest(pubKeyBytes));
Blake2b.Digest blake2b3 = Blake2b.Digest.newInstance(4);
String checksum = HexUtil.encodeHexStr(blake2b3.digest(HexUtil.decodeHex(pubKeyHash)));
return "f1" + Base32.encode(HexUtil.decodeHex(hash + checksum)).toLowerCase();
}
private String fromECKey(ECKey key) {
byte[] pubKeyBytes = key.getPubKey();
return publicKeyToAddress(pubKeyBytes);
}
@Override
public String fromPrivateKey(String prvKeyHex) {
ECKey key = ECKey.fromPrivate(NumericUtil.hexToBytes(prvKeyHex));
return fromECKey(key);
}
@Override
public String fromPrivateKey(byte[] prvKeyBytes) {
ECKey key = ECKey.fromPrivate(prvKeyBytes);
return fromECKey(key);
}
}
| 1,366 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
EthereumAddressCreator.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/address/EthereumAddressCreator.java | package org.consenlabs.tokencore.wallet.address;
import org.bitcoinj.core.ECKey;
import org.consenlabs.tokencore.foundation.crypto.Hash;
import org.consenlabs.tokencore.foundation.utils.NumericUtil;
import java.math.BigInteger;
import java.util.Arrays;
public class EthereumAddressCreator implements AddressCreator {
private static final int PUBLIC_KEY_SIZE = 64;
private static final int PUBLIC_KEY_LENGTH_IN_HEX = PUBLIC_KEY_SIZE << 1;
private static final int ADDRESS_LENGTH = 20;
private static final int ADDRESS_LENGTH_IN_HEX = ADDRESS_LENGTH << 1;
public String fromPublicKey(BigInteger publicKey) {
byte[] pubKeyBytes = NumericUtil.bigIntegerToBytesWithZeroPadded(publicKey, PUBLIC_KEY_SIZE);
return publicKeyToAddress(pubKeyBytes);
}
private String publicKeyToAddress(byte[] pubKeyBytes) {
byte[] hashedBytes = Hash.keccak256(pubKeyBytes);
byte[] addrBytes = Arrays.copyOfRange(hashedBytes, hashedBytes.length - 20, hashedBytes.length);
return NumericUtil.bytesToHex(addrBytes);
}
@Override
public String fromPrivateKey(String prvKeyHex) {
ECKey key = ECKey.fromPrivate(NumericUtil.hexToBytes(prvKeyHex), false);
return fromECKey(key);
}
@Override
public String fromPrivateKey(byte[] prvKeyBytes) {
ECKey key = ECKey.fromPrivate(prvKeyBytes, false);
return fromECKey(key);
}
private String fromECKey(ECKey key) {
byte[] pubKeyBytes = key.getPubKey();
return publicKeyToAddress(Arrays.copyOfRange(pubKeyBytes, 1, pubKeyBytes.length));
}
}
| 1,579 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
LegacyEOSKeystore.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/keystore/LegacyEOSKeystore.java | package org.consenlabs.tokencore.wallet.keystore;
import com.google.common.base.Strings;
import org.consenlabs.tokencore.foundation.crypto.Crypto;
import org.consenlabs.tokencore.wallet.model.ChainType;
import org.consenlabs.tokencore.wallet.model.KeyPair;
import org.consenlabs.tokencore.wallet.model.Metadata;
import org.consenlabs.tokencore.wallet.model.TokenException;
import org.consenlabs.tokencore.wallet.transaction.EOSKey;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
@Deprecated
public class LegacyEOSKeystore extends V3Keystore {
public LegacyEOSKeystore() {
}
public static LegacyEOSKeystore create(Metadata metadata, String accountName, String password, String prvKeyHex) {
return new LegacyEOSKeystore(metadata, accountName, password, prvKeyHex, "");
}
public List<KeyPair> exportPrivateKeys(String password) {
byte[] decrypted = decryptCiphertext(password);
String wif = new String(decrypted);
EOSKey key = EOSKey.fromWIF(wif);
KeyPair keyPair = new KeyPair();
keyPair.setPrivateKey(wif);
keyPair.setPublicKey(key.getPublicKeyAsHex());
return Collections.singletonList(keyPair);
}
@Deprecated
public LegacyEOSKeystore(Metadata metadata, String address, String password, String prvKeyHex, String id) {
if (!metadata.getChainType().equals(ChainType.EOS)) {
throw new TokenException("Only init eos keystore in this constructor");
}
byte[] prvKeyBytes = prvKeyHex.getBytes();
this.address = address;
this.crypto = Crypto.createPBKDF2Crypto(password, prvKeyBytes);
metadata.setWalletType(Metadata.V3);
this.metadata = metadata;
this.version = VERSION;
this.id = Strings.isNullOrEmpty(id) ? UUID.randomUUID().toString() : id;
}
}
| 1,913 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
HDMnemonicKeystore.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/keystore/HDMnemonicKeystore.java | package org.consenlabs.tokencore.wallet.keystore;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.io.BaseEncoding;
import com.subgraph.orchid.encoders.Hex;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.crypto.ChildNumber;
import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.crypto.HDKeyDerivation;
import org.bitcoinj.wallet.DeterministicKeyChain;
import org.bitcoinj.wallet.DeterministicSeed;
import org.consenlabs.tokencore.foundation.crypto.AES;
import org.consenlabs.tokencore.foundation.crypto.Crypto;
import org.consenlabs.tokencore.foundation.crypto.EncPair;
import org.consenlabs.tokencore.foundation.utils.DateUtil;
import org.consenlabs.tokencore.foundation.utils.MetaUtil;
import org.consenlabs.tokencore.foundation.utils.MnemonicUtil;
import org.consenlabs.tokencore.wallet.address.SegWitBitcoinAddressCreator;
import org.consenlabs.tokencore.wallet.model.BIP44Util;
import org.consenlabs.tokencore.wallet.model.Messages;
import org.consenlabs.tokencore.wallet.model.Metadata;
import org.consenlabs.tokencore.wallet.model.TokenException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
/**
* Created by xyz on 2018/2/5.
*/
public final class HDMnemonicKeystore extends IMTKeystore implements EncMnemonicKeystore {
// !!! Don't use this key in production !!!
public static String XPubCommonKey128 = "B888D25EC8C12BD5043777B1AC49F872";
public static String XPubCommonIv = "9C0C30889CBCC5E01AB5B2BB88715799";
static int VERSION = 44;
private EncPair encMnemonic;
private String mnemonicPath;
private String xpub;
public Info getInfo() {
return info;
}
public void setInfo(Info info) {
this.info = info;
}
private Info info;
@Override
public EncPair getEncMnemonic() {
return encMnemonic;
}
@Override
public void setEncMnemonic(EncPair encMnemonic) {
this.encMnemonic = encMnemonic;
}
@Override
public String getMnemonicPath() {
return mnemonicPath;
}
public void setMnemonicPath(String mnemonicPath) {
this.mnemonicPath = mnemonicPath;
}
public String getXpub() {
return this.xpub;
}
public void setXpub(String xpub) {
this.xpub = xpub;
}
public HDMnemonicKeystore() {
super();
}
public static HDMnemonicKeystore create(Metadata metadata, String password, List<String> mnemonics, String path) {
return new HDMnemonicKeystore(metadata, password, mnemonics, path, "");
}
public HDMnemonicKeystore(Metadata metadata, String password, List<String> mnemonics, String path, String id) {
MnemonicUtil.validateMnemonics(mnemonics);
DeterministicSeed seed = new DeterministicSeed(mnemonics, null, "", 0L);
DeterministicKeyChain keyChain = DeterministicKeyChain.builder().seed(seed).build();
this.mnemonicPath = path;
DeterministicKey parent = keyChain.getKeyByPath(BIP44Util.generatePath(path), true);
NetworkParameters networkParameters = MetaUtil.getNetWork(metadata);
this.xpub = parent.serializePubB58(networkParameters);
String xprv = parent.serializePrivB58(networkParameters);
DeterministicKey mainAddressKey = keyChain.getKeyByPath(BIP44Util.generatePath(path + "/0/0"), true);
if (Metadata.P2WPKH.equals(metadata.getSegWit())) {
this.address = new SegWitBitcoinAddressCreator(networkParameters).fromPrivateKey(mainAddressKey.getPrivateKeyAsHex());
} else {
this.address = mainAddressKey.toAddress(networkParameters).toBase58();
}
if (metadata.getTimestamp() == 0) {
metadata.setTimestamp(DateUtil.getUTCTime());
}
metadata.setWalletType(Metadata.HD);
this.crypto = Crypto.createPBKDF2CryptoWithKDFCached(password, xprv.getBytes(Charset.forName("UTF-8")));
this.metadata = metadata;
this.encMnemonic = crypto.deriveEncPair(password, Joiner.on(" ").join(mnemonics).getBytes());
this.crypto.clearCachedDerivedKey();
this.version = VERSION;
this.info = new Info();
this.id = Strings.isNullOrEmpty(id) ? UUID.randomUUID().toString() : id;
}
@Override
public Keystore changePassword(String oldPassword, String newPassword) {
String mnemonic = new String(getCrypto().decryptEncPair(oldPassword, encMnemonic));
List<String> mnemonicCodes = Arrays.asList(mnemonic.split(" "));
return new HDMnemonicKeystore(metadata, newPassword, mnemonicCodes, this.mnemonicPath, this.id);
}
@JsonIgnore
public String getEncryptXPub() {
String plainText = this.xpub;
try {
byte[] commonKey128 = Hex.decode(XPubCommonKey128);
byte[] clean = plainText.getBytes();
byte[] commonIv = Hex.decode(XPubCommonIv);
byte[] encrypted = AES.encryptByCBC(clean, commonKey128, commonIv);
return BaseEncoding.base64().encode(encrypted);
} catch (Exception ex) {
throw new TokenException(Messages.ENCRYPT_XPUB_ERROR);
}
}
public String newReceiveAddress(int nextIdx) {
NetworkParameters networkParameters = MetaUtil.getNetWork(this.metadata);
DeterministicKey key = DeterministicKey.deserializeB58(this.xpub, networkParameters);
DeterministicKey changeKey = HDKeyDerivation.deriveChildKey(key, ChildNumber.ZERO);
DeterministicKey indexKey = HDKeyDerivation.deriveChildKey(changeKey, new ChildNumber(nextIdx));
if (Metadata.P2WPKH.equals(metadata.getSegWit())) {
return new SegWitBitcoinAddressCreator(networkParameters).fromPrivateKey(indexKey).toBase58();
} else {
return indexKey.toAddress(networkParameters).toBase58();
}
}
public static class Info {
private String curve = "spec256k1";
private String purpuse = "sign";
public Info() {
}
public String getCurve() {
return curve;
}
public void setCurve(String curve) {
this.curve = curve;
}
public String getPurpuse() {
return purpuse;
}
public void setPurpuse(String purpuse) {
this.purpuse = purpuse;
}
}
}
| 6,248 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
IdentityKeystore.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/keystore/IdentityKeystore.java | package org.consenlabs.tokencore.wallet.keystore;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.google.common.base.Joiner;
import org.bitcoinj.core.Base58;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.Sha256Hash;
import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.crypto.HDKeyDerivation;
import org.bitcoinj.wallet.DeterministicSeed;
import org.consenlabs.tokencore.foundation.crypto.Crypto;
import org.consenlabs.tokencore.foundation.crypto.EncPair;
import org.consenlabs.tokencore.foundation.crypto.Hash;
import org.consenlabs.tokencore.foundation.crypto.Multihash;
import org.consenlabs.tokencore.foundation.utils.*;
import org.consenlabs.tokencore.wallet.model.Metadata;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by xyz on 2017/12/11.
*/
public class IdentityKeystore extends Keystore implements EncMnemonicKeystore {
private static final int VERSION = 10000;
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public void setWalletIDs(List<String> walletIDs) {
this.walletIDs = walletIDs;
}
public void setIpfsId(String ipfsId) {
this.ipfsId = ipfsId;
}
public void setEncKey(String encKey) {
this.encKey = encKey;
}
public void setEncAuthKey(EncPair encAuthKey) {
this.encAuthKey = encAuthKey;
}
public void setMnemonicPath(String mnemonicPath) {
this.mnemonicPath = mnemonicPath;
}
private String identifier;
private String ipfsId;
private String encKey;
private EncPair encAuthKey;
private EncPair encMnemonic;
private String mnemonicPath;
public void setMetadata(Metadata metadata) {
this.metadata = metadata;
}
private Metadata metadata;
private List<String> walletIDs = new ArrayList<>();
public IdentityKeystore() {
}
public IdentityKeystore(Metadata metadata, List<String> mnemonicCodes, String password) {
MnemonicUtil.validateMnemonics(mnemonicCodes);
DeterministicSeed seed = new DeterministicSeed(mnemonicCodes, null, "", 0L);
DeterministicKey masterPrivateKey = HDKeyDerivation.createMasterPrivateKey(seed.getSeedBytes());
byte[] masterKey = masterPrivateKey.getPrivKeyBytes();
String salt = metadata.isMainNet() ? "Automatic Backup Key Mainnet" : "Automatic Backup Key Testnet";
byte[] backupKey = Hash.hmacSHA256(masterKey, salt.getBytes(Charset.forName("ASCII")));
byte[] authenticationKey = Hash.hmacSHA256(backupKey, "Authentication Key".getBytes(Charset.forName("UTF-8")));
ECKey authKey = ECKey.fromPrivate(authenticationKey);
NetworkParameters networkParameters = MetaUtil.getNetWork(metadata);
String aPubHashHex = NumericUtil.bytesToHex(authKey.getPubKeyHash());
int networkHeader = networkParameters.getAddressHeader();
int version = 2;
// this magic hex will start with 'im' after base58check
String magicHex = "0fdc0c";
String fullIdentifier = String.format("%s%02x%02x%s", magicHex, (byte) networkHeader, (byte) version, aPubHashHex);
byte[] fullIdentifierBytes = NumericUtil.hexToBytes(fullIdentifier);
byte[] checksumBytes = Arrays.copyOfRange(Sha256Hash.hashTwice(fullIdentifierBytes), 0, 4);
byte[] identifierWithChecksum = ByteUtil.concat(fullIdentifierBytes, checksumBytes);
this.identifier = Base58.encode(identifierWithChecksum);
byte[] encKeyFullBytes = Hash.hmacSHA256(backupKey, "Encryption Key".getBytes(Charset.forName("UTF-8")));
this.encKey = NumericUtil.bytesToHex(encKeyFullBytes);
ECKey ecKey = ECKey.fromPrivate(encKeyFullBytes, false);
this.ipfsId = new Multihash(Multihash.Type.sha2_256, Hash.sha256(ecKey.getPubKey())).toBase58();
Crypto crypto = Crypto.createPBKDF2CryptoWithKDFCached(password, masterPrivateKey.serializePrivB58(networkParameters).getBytes(Charset.forName("UTF-8")));
this.encAuthKey = crypto.deriveEncPair(password, authenticationKey);
this.encMnemonic = crypto.deriveEncPair(password, Joiner.on(" ").join(mnemonicCodes).getBytes());
crypto.clearCachedDerivedKey();
metadata.setTimestamp(DateUtil.getUTCTime());
metadata.setSegWit(null);
this.metadata = metadata;
this.crypto = crypto;
this.version = VERSION;
this.walletIDs = new ArrayList<>();
}
@Override
public EncPair getEncMnemonic() {
return this.encMnemonic;
}
@Override
public void setEncMnemonic(EncPair encMnemonic) {
this.encMnemonic = encMnemonic;
}
@Override
public String getMnemonicPath() {
return this.mnemonicPath;
}
public List<String> getWalletIDs() {
return walletIDs;
}
@JsonGetter(value = "imTokenMeta")
public Metadata getMetadata() {
return metadata;
}
public String getIdentifier() {
return identifier;
}
public String getIpfsId() {
return ipfsId;
}
public String getEncKey() {
return encKey;
}
public EncPair getEncAuthKey() {
return encAuthKey;
}
}
| 5,191 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
V3Keystore.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/keystore/V3Keystore.java | package org.consenlabs.tokencore.wallet.keystore;
import com.google.common.base.Strings;
import org.bitcoinj.core.NetworkParameters;
import org.consenlabs.tokencore.foundation.crypto.Crypto;
import org.consenlabs.tokencore.foundation.utils.MetaUtil;
import org.consenlabs.tokencore.foundation.utils.NumericUtil;
import org.consenlabs.tokencore.wallet.address.BitcoinAddressCreator;
import org.consenlabs.tokencore.wallet.address.EthereumAddressCreator;
import org.consenlabs.tokencore.wallet.address.SegWitBitcoinAddressCreator;
import org.consenlabs.tokencore.wallet.address.TronAddressCreator;
import org.consenlabs.tokencore.wallet.model.ChainType;
import org.consenlabs.tokencore.wallet.model.Metadata;
import org.consenlabs.tokencore.wallet.model.TokenException;
import org.consenlabs.tokencore.wallet.validators.PrivateKeyValidator;
import org.consenlabs.tokencore.wallet.validators.WIFValidator;
import java.util.UUID;
/**
* Created by xyz on 2018/2/5.
*/
public class V3Keystore extends IMTKeystore implements ExportableKeystore {
public static final int VERSION = 3;
public V3Keystore() {
}
public static V3Keystore create(Metadata metadata, String password, String prvKeyHex) {
return new V3Keystore(metadata, password, prvKeyHex, "");
}
public V3Keystore(Metadata metadata, String password, String prvKeyHex, String id) {
byte[] prvKeyBytes;
if (metadata.getChainType().equals(ChainType.BITCOIN) ||
metadata.getChainType().equals(ChainType.LITECOIN) ||
metadata.getChainType().equals(ChainType.DASH) ||
metadata.getChainType().equals(ChainType.DOGECOIN) ||
metadata.getChainType().equals(ChainType.BITCOINCASH) ||
metadata.getChainType().equals(ChainType.BITCOINSV)) {
NetworkParameters network = MetaUtil.getNetWork(metadata);
prvKeyBytes = prvKeyHex.getBytes();
new WIFValidator(prvKeyHex, network).validate();
if (Metadata.P2WPKH.equals(metadata.getSegWit())) {
this.address = new SegWitBitcoinAddressCreator(network).fromPrivateKey(prvKeyHex);
} else {
this.address = new BitcoinAddressCreator(network).fromPrivateKey(prvKeyHex);
}
} else if (metadata.getChainType().equals(ChainType.ETHEREUM)) {
prvKeyBytes = NumericUtil.hexToBytes(prvKeyHex);
new PrivateKeyValidator(prvKeyHex).validate();
this.address = new EthereumAddressCreator().fromPrivateKey(prvKeyBytes);
} else if (metadata.getChainType().equals(ChainType.TRON)) {
prvKeyBytes = NumericUtil.hexToBytes(prvKeyHex);
new PrivateKeyValidator(prvKeyHex).validate();
this.address = new TronAddressCreator().fromPrivateKey(prvKeyBytes);
}else {
throw new TokenException("Can't init eos keystore in this constructor");
}
this.crypto = Crypto.createPBKDF2Crypto(password, prvKeyBytes);
metadata.setWalletType(Metadata.V3);
this.metadata = metadata;
this.version = VERSION;
this.id = Strings.isNullOrEmpty(id) ? UUID.randomUUID().toString() : id;
}
@Override
public Keystore changePassword(String oldPassword, String newPassword) {
byte[] decrypted = this.crypto.decrypt(oldPassword);
String prvKeyHex;
if (Metadata.FROM_WIF.equals(getMetadata().getSource())) {
prvKeyHex = new String(decrypted);
} else {
prvKeyHex = NumericUtil.bytesToHex(decrypted);
}
return new V3Keystore(metadata, newPassword, prvKeyHex, this.id);
}
}
| 3,759 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
WalletKeystore.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/keystore/WalletKeystore.java | package org.consenlabs.tokencore.wallet.keystore;
public abstract class WalletKeystore extends Keystore {
String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public abstract Keystore changePassword(String oldPassword, String newPassword);
public WalletKeystore() { super();}
}
| 399 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
Keystore.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/keystore/Keystore.java | package org.consenlabs.tokencore.wallet.keystore;
import org.consenlabs.tokencore.foundation.crypto.Crypto;
import java.util.UUID;
/**
* Created by xyz on 2018/2/5.
*/
public abstract class Keystore {
String id;
int version;
Crypto crypto;
public Keystore() {
this.id = UUID.randomUUID().toString();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public Crypto getCrypto() {
return crypto;
}
public void setCrypto(Crypto crypto) {
this.crypto = crypto;
}
public boolean verifyPassword(String password) {
return getCrypto().verifyPassword(password);
}
public byte[] decryptCiphertext(String password) {
return getCrypto().decrypt(password);
}
}
| 947 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
V3MnemonicKeystore.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/keystore/V3MnemonicKeystore.java | package org.consenlabs.tokencore.wallet.keystore;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import org.bitcoinj.crypto.ChildNumber;
import org.bitcoinj.wallet.DeterministicKeyChain;
import org.bitcoinj.wallet.DeterministicSeed;
import org.consenlabs.tokencore.foundation.crypto.Crypto;
import org.consenlabs.tokencore.foundation.crypto.EncPair;
import org.consenlabs.tokencore.foundation.utils.DateUtil;
import org.consenlabs.tokencore.foundation.utils.MnemonicUtil;
import org.consenlabs.tokencore.wallet.address.AddressCreatorManager;
import org.consenlabs.tokencore.wallet.model.BIP44Util;
import org.consenlabs.tokencore.wallet.model.Metadata;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
/**
* Created by xyz on 2018/2/5.
*/
public class V3MnemonicKeystore extends IMTKeystore implements EncMnemonicKeystore, ExportableKeystore {
private static final int VERSION = 3;
private EncPair encMnemonic;
private String mnemonicPath;
@Override
public EncPair getEncMnemonic() {
return encMnemonic;
}
@Override
public void setEncMnemonic(EncPair encMnemonic) {
this.encMnemonic = encMnemonic;
}
@Override
public String getMnemonicPath() {
return this.mnemonicPath;
}
public void setMnemonicPath(String mnemonicPath) {
this.mnemonicPath = mnemonicPath;
}
public V3MnemonicKeystore() {
super();
}
public static V3MnemonicKeystore create(Metadata metadata, String password, List<String> mnemonicCodes, String path) {
return new V3MnemonicKeystore(metadata, password, mnemonicCodes, path, "");
}
private V3MnemonicKeystore(Metadata metadata, String password, List<String> mnemonicCodes, String path, String id) {
MnemonicUtil.validateMnemonics(mnemonicCodes);
DeterministicSeed seed = new DeterministicSeed(mnemonicCodes, null, "", 0L);
DeterministicKeyChain keyChain = DeterministicKeyChain.builder().seed(seed).build();
this.mnemonicPath = path;
List<ChildNumber> zeroPath = BIP44Util.generatePath(path);
byte[] prvKeyBytes = keyChain.getKeyByPath(zeroPath, true).getPrivKeyBytes();
this.crypto = Crypto.createPBKDF2CryptoWithKDFCached(password, prvKeyBytes);
this.encMnemonic = crypto.deriveEncPair(password, Joiner.on(" ").join(mnemonicCodes).getBytes());
this.crypto.clearCachedDerivedKey();
this.address = AddressCreatorManager.getInstance(metadata.getChainType(), metadata.isMainNet(), metadata.getSegWit()).fromPrivateKey(prvKeyBytes);
metadata.setTimestamp(DateUtil.getUTCTime());
metadata.setWalletType(Metadata.V3);
this.metadata = metadata;
this.version = VERSION;
this.id = Strings.isNullOrEmpty(id) ? UUID.randomUUID().toString() : id;
}
@Override
public Keystore changePassword(String oldPassword, String newPassword) {
String mnemonic = new String(getCrypto().decryptEncPair(oldPassword, this.getEncMnemonic()));
List<String> mnemonicCodes = Arrays.asList(mnemonic.split(" "));
return new V3MnemonicKeystore(this.metadata, newPassword, mnemonicCodes, this.mnemonicPath, this.id);
}
}
| 3,201 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
V3Ignore.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/keystore/V3Ignore.java | package org.consenlabs.tokencore.wallet.keystore;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.consenlabs.tokencore.foundation.crypto.EncPair;
import org.consenlabs.tokencore.wallet.model.Metadata;
/**
* Created by xyz on 2018/2/8.
*/
public abstract class V3Ignore {
@JsonIgnore
public abstract EncPair getEncMnemonic();
@JsonIgnore
@JsonGetter(value = "imTokenMeta")
public abstract Metadata getMetadata();
@JsonIgnore
public abstract String getMnemonicPath();
@JsonIgnore
public abstract String getEncXPub();
@JsonIgnore
public abstract int getMnemonicIndex();
}
| 693 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
EncMnemonicKeystore.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/keystore/EncMnemonicKeystore.java | package org.consenlabs.tokencore.wallet.keystore;
import org.consenlabs.tokencore.foundation.crypto.Crypto;
import org.consenlabs.tokencore.foundation.crypto.EncPair;
import java.nio.charset.Charset;
public interface EncMnemonicKeystore {
EncPair getEncMnemonic();
void setEncMnemonic(EncPair encMnemonic);
String getMnemonicPath();
Crypto getCrypto();
default void createEncMnemonic(String password, String mnemonic) {
EncPair encMnemonic = getCrypto().deriveEncPair(password, mnemonic.getBytes(Charset.forName("UTF-8")));
this.setEncMnemonic(encMnemonic);
}
default String decryptMnemonic(String password) {
return new String(getCrypto().decryptEncPair(password, getEncMnemonic()));
}
}
| 746 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
EOSKeystore.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/keystore/EOSKeystore.java | package org.consenlabs.tokencore.wallet.keystore;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import org.bitcoinj.wallet.DeterministicKeyChain;
import org.bitcoinj.wallet.DeterministicSeed;
import org.consenlabs.tokencore.foundation.crypto.Crypto;
import org.consenlabs.tokencore.foundation.crypto.EncPair;
import org.consenlabs.tokencore.foundation.utils.DateUtil;
import org.consenlabs.tokencore.foundation.utils.MnemonicUtil;
import org.consenlabs.tokencore.foundation.utils.NumericUtil;
import org.consenlabs.tokencore.wallet.model.*;
import org.consenlabs.tokencore.wallet.transaction.EOSKey;
import java.util.*;
import java.util.regex.Pattern;
public class EOSKeystore extends IMTKeystore implements EncMnemonicKeystore {
// the version = IdentityVersion + 1;
static int VERSION = 10001;
private static final String PERM_OWNER = "owner";
private static final String PERM_ACTIVE = "active";
private EncPair encMnemonic;
private String mnemonicPath;
private List<KeyPathPrivate> mKeyPathPrivates = new ArrayList<>();
public List<KeyPathPrivate> getKeyPathPrivates() {
return mKeyPathPrivates;
}
public void setKeyPathPrivates(List<KeyPathPrivate> keyPathPrivates) {
this.mKeyPathPrivates = keyPathPrivates;
}
@Override
public EncPair getEncMnemonic() {
return encMnemonic;
}
@Override
public void setEncMnemonic(EncPair encMnemonic) {
this.encMnemonic = encMnemonic;
}
@Override
public String getMnemonicPath() {
return mnemonicPath;
}
@Override
public Keystore changePassword(String oldPassword, String newPassword) {
return null;
}
public EOSKeystore() {
super();
}
public static EOSKeystore create(Metadata metadata, String password, String accountName, List<String> mnemonics, String path, List<PermissionObject> permissions) {
return new EOSKeystore(metadata, password, accountName, mnemonics, path, permissions, "");
}
public static EOSKeystore create(Metadata metadata, String password, String accountName, List<String> mnemonics, String path, List<PermissionObject> permissions, String id) {
return new EOSKeystore(metadata, password, accountName, mnemonics, path, permissions, id);
}
public static EOSKeystore create(Metadata metadata, String password, String accountName, List<String> prvKeys, List<PermissionObject> permissions) {
return new EOSKeystore(metadata, password, accountName, prvKeys, permissions, "");
}
public List<KeyPair> exportPrivateKeys(String password) {
List<KeyPair> keyPairs = new ArrayList<>(mKeyPathPrivates.size());
crypto.cacheDerivedKey(password);
for (KeyPathPrivate keyPathPrivate : mKeyPathPrivates) {
KeyPair keyPair = new KeyPair();
byte[] prvKeyBytes = crypto.decryptEncPair(password, keyPathPrivate.encPrivate);
String wif = EOSKey.fromPrivate(prvKeyBytes).toBase58();
keyPair.setPrivateKey(wif);
keyPair.setPublicKey(keyPathPrivate.publicKey);
keyPairs.add(keyPair);
}
crypto.clearCachedDerivedKey();
return keyPairs;
}
private EOSKeystore(Metadata metadata, String password, String accountName, List<String> prvKeys, List<PermissionObject> permissions, String id) {
this.crypto = Crypto.createPBKDF2CryptoWithKDFCached(password, NumericUtil.generateRandomBytes(128));
this.encMnemonic = null;
this.mnemonicPath = null;
if (metadata.getTimestamp() == 0) {
metadata.setTimestamp(DateUtil.getUTCTime());
}
Set<String> permPubKeys = new HashSet<>(permissions.size());
for (PermissionObject permissionObject : permissions) {
permPubKeys.add(permissionObject.publicKey);
}
for (String prvKey : prvKeys) {
EOSKey eosKey = EOSKey.fromWIF(prvKey);
String pubKey = eosKey.getPublicKeyAsHex();
if (!permPubKeys.contains(pubKey)) {
throw new TokenException(Messages.EOS_PRIVATE_PUBLIC_NOT_MATCH);
}
KeyPathPrivate keyPath = new KeyPathPrivate();
keyPath.publicKey = pubKey;
keyPath.encPrivate = crypto.deriveEncPair(password, eosKey.getPrivateKey());
keyPath.derivedMode = KeyPathPrivate.IMPORTED;
this.mKeyPathPrivates.add(keyPath);
}
this.crypto.clearCachedDerivedKey();
metadata.setWalletType(Metadata.RANDOM);
this.metadata = metadata;
this.version = VERSION;
if (!Strings.isNullOrEmpty(accountName)) {
setAccountName(accountName);
}
this.id = Strings.isNullOrEmpty(id) ? UUID.randomUUID().toString() : id;
}
private EOSKeystore(Metadata metadata, String password, String accountName, List<String> mnemonics, String path, List<PermissionObject> permissions, String id) {
MnemonicUtil.validateMnemonics(mnemonics);
this.mnemonicPath = path;
List<KeyPath> allDefaultKeys = calcAllDefaultKeys(mnemonics);
byte[] masterPrivateKeyBytes = NumericUtil.generateRandomBytes(16);
if (metadata.getTimestamp() == 0) {
metadata.setTimestamp(DateUtil.getUTCTime());
}
metadata.setWalletType(Metadata.HD);
this.crypto = Crypto.createPBKDF2CryptoWithKDFCached(password, masterPrivateKeyBytes);
this.metadata = metadata;
this.encMnemonic = crypto.deriveEncPair(password, Joiner.on(" ").join(mnemonics).getBytes());
this.derivedKeyPath(allDefaultKeys, permissions, password);
this.crypto.clearCachedDerivedKey();
if (!Strings.isNullOrEmpty(accountName)) {
setAccountName(accountName);
}
this.version = VERSION;
this.id = Strings.isNullOrEmpty(id) ? UUID.randomUUID().toString() : id;
}
private void derivedKeyPath(List<KeyPath> keyPaths, List<PermissionObject> permissions, String password) {
for (KeyPath keyPath : keyPaths) {
EncPair encPair = crypto.deriveEncPair(password, keyPath.getPrivateKey());
String publicKey = EOSKey.fromPrivate(keyPath.getPrivateKey()).getPublicKeyAsHex();
String derivedMode = Strings.isNullOrEmpty(keyPath.getPath()) ? KeyPathPrivate.HD_SHA256 : KeyPathPrivate.PATH_DIRECTLY;
KeyPathPrivate keyPathPrivate = new KeyPathPrivate(encPair, publicKey, keyPath.getPath(), derivedMode);
mKeyPathPrivates.add(keyPathPrivate);
}
if (permissions != null) {
for (PermissionObject perm : permissions) {
if (PERM_OWNER.equalsIgnoreCase(perm.permission) || PERM_ACTIVE.equalsIgnoreCase(perm.permission)) {
boolean isContainsPermission = false;
for (KeyPathPrivate keyPathPrivate : mKeyPathPrivates) {
if (keyPathPrivate.getPublicKey().equals(perm.publicKey)) {
isContainsPermission = true;
}
}
if (!isContainsPermission) {
throw new TokenException(Messages.EOS_PRIVATE_PUBLIC_NOT_MATCH);
}
}
}
}
}
public byte[] decryptPrivateKeyFor(String pubKey, String password) {
EncPair targetPair = null;
for (KeyPathPrivate privatePath : mKeyPathPrivates) {
if (privatePath.publicKey.equals(pubKey)) {
targetPair = privatePath.encPrivate;
break;
}
}
if (targetPair == null) {
throw new TokenException(Messages.EOS_PUBLIC_KEY_NOT_FOUND);
}
return this.crypto.decryptEncPair(password, targetPair);
}
public void setAccountName(String accountName) {
if (!Strings.isNullOrEmpty(this.address) && !this.address.equals(accountName)) {
throw new TokenException("Only can set accountName once in eos wallet");
}
if (!Pattern.matches("[1-5a-z.]{1,12}", accountName)) {
throw new TokenException(Messages.EOS_ACCOUNT_NAME_INVALID);
}
this.address = accountName;
}
// calc default keys
private List<KeyPath> calcAllDefaultKeys(List<String> mnemonics) {
DeterministicSeed seed = new DeterministicSeed(mnemonics, null, "", 0L);
DeterministicKeyChain rootKeyChain = DeterministicKeyChain.builder().seed(seed).build();
List<KeyPath> defaultKeys = calcDefaultKeys(rootKeyChain, this.mnemonicPath);
return defaultKeys;
}
private static List<KeyPath> calcDefaultKeys(DeterministicKeyChain rootKeyChain, String path) {
String[] subpaths = path.split(",");
List<KeyPath> result = new ArrayList<>(subpaths.length);
for (String subpath : subpaths) {
byte[] prvKeyBytes = rootKeyChain.getKeyByPath(BIP44Util.generatePath(subpath), true).getPrivKeyBytes();
result.add(new KeyPath(prvKeyBytes, subpath));
}
return result;
}
public static class KeyPathPrivate {
public final static String PATH_DIRECTLY = "PATH_DIRECTLY";
public final static String IMPORTED = "IMPORTED";
public final static String HD_SHA256 = "HD_SHA256";
private EncPair encPrivate;
private String publicKey;
private String path;
private String derivedMode;
public KeyPathPrivate() {
}
public KeyPathPrivate(EncPair encPrivate, String publicKey, String path, String derivedMode) {
this.encPrivate = encPrivate;
this.publicKey = publicKey;
this.path = path;
this.derivedMode = derivedMode;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getDerivedMode() {
return derivedMode;
}
public void setDerivedMode(String derivedMode) {
this.derivedMode = derivedMode;
}
public EncPair getEncPrivate() {
return encPrivate;
}
public void setEncPrivate(EncPair encPrivate) {
this.encPrivate = encPrivate;
}
public String getPublicKey() {
return publicKey;
}
public void setPublicKey(String publicKey) {
this.publicKey = publicKey;
}
}
public static class KeyPath {
byte[] privateKey;
String path;
public KeyPath(byte[] privateKey, String path) {
this.privateKey = privateKey;
this.path = path;
}
public byte[] getPrivateKey() {
return privateKey;
}
public void setPrivateKey(byte[] privateKey) {
this.privateKey = privateKey;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
public static class PermissionObject {
String permission;
String publicKey;
String parent;
public String getParent() {
return parent;
}
public void setParent(String parent) {
this.parent = parent;
}
public String getPermission() {
return permission;
}
public void setPermission(String permission) {
this.permission = permission;
}
public String getPublicKey() {
return publicKey;
}
public void setPublicKey(String publicKey) {
this.publicKey = publicKey;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PermissionObject that = (PermissionObject) o;
return Objects.equals(permission, that.permission) &&
Objects.equals(publicKey, that.publicKey) &&
Objects.equals(parent, that.parent);
}
@Override
public int hashCode() {
return Objects.hash(permission, publicKey, parent);
}
}
}
| 11,557 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
IMTKeystore.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/keystore/IMTKeystore.java | package org.consenlabs.tokencore.wallet.keystore;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.consenlabs.tokencore.wallet.model.Metadata;
public abstract class IMTKeystore extends WalletKeystore {
@JsonIgnore
Metadata metadata;
@JsonGetter(value = "imTokenMeta")
public Metadata getMetadata() {
return metadata;
}
public void setMetadata(Metadata metadata) {
this.metadata = metadata;
}
public IMTKeystore() {
super();
}
}
| 552 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
EthereumTransaction.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/transaction/EthereumTransaction.java | package org.consenlabs.tokencore.wallet.transaction;
import org.consenlabs.tokencore.foundation.crypto.Hash;
import org.consenlabs.tokencore.foundation.rlp.RlpEncoder;
import org.consenlabs.tokencore.foundation.rlp.RlpList;
import org.consenlabs.tokencore.foundation.rlp.RlpString;
import org.consenlabs.tokencore.foundation.rlp.RlpType;
import org.consenlabs.tokencore.foundation.utils.ByteUtil;
import org.consenlabs.tokencore.foundation.utils.NumericUtil;
import org.consenlabs.tokencore.wallet.Wallet;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
/**
* Transaction class used for signing transactions locally.<br>
* For the specification, refer to p4 of the <a href="http://gavwood.com/paper.pdf">
* <p>
* yellow paper</a>.
*/
public class EthereumTransaction implements TransactionSigner {
private BigInteger nonce;
private BigInteger gasPrice;
private BigInteger gasLimit;
private String to;
private BigInteger value;
private String data;
public EthereumTransaction(BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, String to,
BigInteger value, String data) {
this.nonce = nonce;
this.gasPrice = gasPrice;
this.gasLimit = gasLimit;
this.to = to;
this.value = value;
if (data != null) {
this.data = NumericUtil.cleanHexPrefix(data);
}
}
public BigInteger getNonce() {
return nonce;
}
public BigInteger getGasPrice() {
return gasPrice;
}
public BigInteger getGasLimit() {
return gasLimit;
}
public String getTo() {
return to;
}
public BigInteger getValue() {
return value;
}
public String getData() {
return data;
}
@Override
public TxSignResult signTransaction(String chainID, String password, Wallet wallet) {
String signedTx = signTransaction(Integer.parseInt(chainID), wallet.decryptMainKey(password));
String txHash = this.calcTxHash(signedTx);
return new TxSignResult(signedTx, txHash);
}
String signTransaction(int chainId, byte[] privateKey) {
SignatureData signatureData = new SignatureData(chainId, new byte[]{}, new byte[]{});
byte[] encodedTransaction = encodeToRLP(signatureData);
signatureData = EthereumSign.signMessage(encodedTransaction, privateKey);
SignatureData eip155SignatureData = createEip155SignatureData(signatureData, chainId);
byte[] rawSignedTx = encodeToRLP(eip155SignatureData);
return NumericUtil.bytesToHex(rawSignedTx);
}
String calcTxHash(String signedTx) {
return NumericUtil.prependHexPrefix(Hash.keccak256(signedTx));
}
private static SignatureData createEip155SignatureData(SignatureData signatureData, int chainId) {
int v = signatureData.getV() + (chainId * 2) + 8;
return new SignatureData(v, signatureData.getR(), signatureData.getS());
}
byte[] encodeToRLP(SignatureData signatureData) {
List<RlpType> values = asRlpValues(signatureData);
RlpList rlpList = new RlpList(values);
return RlpEncoder.encode(rlpList);
}
List<RlpType> asRlpValues(SignatureData signatureData) {
List<RlpType> result = new ArrayList<>();
result.add(RlpString.create(getNonce()));
result.add(RlpString.create(getGasPrice()));
result.add(RlpString.create(getGasLimit()));
// an empty to address (contract creation) should not be encoded as a numeric 0 value
String to = getTo();
if (to != null && to.length() > 0) {
// addresses that start with zeros should be encoded with the zeros included, not
// as numeric values
result.add(RlpString.create(NumericUtil.hexToBytes(to)));
} else {
result.add(RlpString.create(""));
}
result.add(RlpString.create(getValue()));
// value field will already be hex encoded, so we need to convert into binary first
byte[] data = NumericUtil.hexToBytes(getData());
result.add(RlpString.create(data));
if (signatureData != null && signatureData.getV() > 0) {
result.add(RlpString.create(signatureData.getV()));
result.add(RlpString.create(ByteUtil.trimLeadingZeroes(signatureData.getR())));
result.add(RlpString.create(ByteUtil.trimLeadingZeroes(signatureData.getS())));
}
return result;
}
}
| 4,376 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
MyHMacDSAKCalculator.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/transaction/MyHMacDSAKCalculator.java | package org.consenlabs.tokencore.wallet.transaction;
import org.spongycastle.crypto.Digest;
import org.spongycastle.crypto.macs.HMac;
import org.spongycastle.crypto.params.KeyParameter;
import org.spongycastle.crypto.signers.DSAKCalculator;
import org.spongycastle.util.Arrays;
import org.spongycastle.util.BigIntegers;
import java.math.BigInteger;
import java.security.SecureRandom;
public class MyHMacDSAKCalculator implements DSAKCalculator {
private static final BigInteger ZERO = BigInteger.valueOf(0);
private final HMac hMac;
private final byte[] K;
private final byte[] V;
private BigInteger n;
private boolean needTry;
/**
* Base constructor.
*
* @param digest digest to build the HMAC on.
*/
public MyHMacDSAKCalculator(Digest digest) {
this.hMac = new HMac(digest);
this.V = new byte[hMac.getMacSize()];
this.K = new byte[hMac.getMacSize()];
}
public boolean isDeterministic() {
return true;
}
public void init(BigInteger n, SecureRandom random) {
throw new IllegalStateException("Operation not supported");
}
public void init(BigInteger n, BigInteger d, byte[] message) {
this.n = n;
this.needTry = false;
Arrays.fill(V, (byte) 0x01);
Arrays.fill(K, (byte) 0);
byte[] x = new byte[(n.bitLength() + 7) / 8];
byte[] dVal = BigIntegers.asUnsignedByteArray(d);
System.arraycopy(dVal, 0, x, x.length - dVal.length, dVal.length);
byte[] m = new byte[(n.bitLength() + 7) / 8];
BigInteger mInt = bitsToInt(message);
if (mInt.compareTo(n) > 0) {
mInt = mInt.subtract(n);
}
byte[] mVal = BigIntegers.asUnsignedByteArray(mInt);
System.arraycopy(mVal, 0, m, m.length - mVal.length, mVal.length);
hMac.init(new KeyParameter(K));
hMac.update(V, 0, V.length);
hMac.update((byte) 0x00);
hMac.update(x, 0, x.length);
hMac.update(m, 0, m.length);
hMac.doFinal(K, 0);
hMac.init(new KeyParameter(K));
hMac.update(V, 0, V.length);
hMac.doFinal(V, 0);
hMac.update(V, 0, V.length);
hMac.update((byte) 0x01);
hMac.update(x, 0, x.length);
hMac.update(m, 0, m.length);
hMac.doFinal(K, 0);
hMac.init(new KeyParameter(K));
hMac.update(V, 0, V.length);
hMac.doFinal(V, 0);
}
public BigInteger nextK() {
byte[] t = new byte[((n.bitLength() + 7) / 8)];
if (needTry) {
hMac.init(new KeyParameter(K));
hMac.update(V, 0, V.length);
hMac.update((byte) 0x00);
hMac.doFinal(K, 0);
hMac.init(new KeyParameter(K));
hMac.update(V, 0, V.length);
hMac.doFinal(V, 0);
}
int tOff = 0;
while (tOff < t.length) {
hMac.init(new KeyParameter(K));
hMac.update(V, 0, V.length);
hMac.doFinal(V, 0);
int len = Math.min(t.length - tOff, V.length);
System.arraycopy(V, 0, t, tOff, len);
tOff += len;
}
BigInteger k = bitsToInt(t);
needTry = true;
return k;
}
private BigInteger bitsToInt(byte[] t) {
BigInteger v = new BigInteger(1, t);
if (t.length * 8 > n.bitLength()) {
v = v.shiftRight(t.length * 8 - n.bitLength());
}
return v;
}
}
| 3,312 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
EOSECDSASigner.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/transaction/EOSECDSASigner.java | package org.consenlabs.tokencore.wallet.transaction;
import org.bitcoinj.core.ECKey;
import org.spongycastle.crypto.CipherParameters;
import org.spongycastle.crypto.params.*;
import org.spongycastle.crypto.signers.DSAKCalculator;
import org.spongycastle.math.ec.ECAlgorithms;
import org.spongycastle.math.ec.ECMultiplier;
import org.spongycastle.math.ec.ECPoint;
import org.spongycastle.math.ec.FixedPointCombMultiplier;
import java.math.BigInteger;
import java.security.SecureRandom;
import static java.math.BigDecimal.ZERO;
import static java.math.BigInteger.ONE;
/**
* !!! We copy the code from BitcoinJ !!!
* EOS extends the data and then hash it by rcf6979 to generate Canonical Signatures.
* The BitcoinJ doesn't expose the same api as libsecp256k1, we can't overwrite it by inheriting
*/
public class EOSECDSASigner {
private final DSAKCalculator kCalculator;
private ECKeyParameters key;
private SecureRandom random;
/**
* Configuration with an alternate, possibly deterministic calculator of K.
*
* @param kCalculator a K value calculator.
*/
public EOSECDSASigner(DSAKCalculator kCalculator) {
this.kCalculator = kCalculator;
}
public void init(
boolean forSigning,
CipherParameters param) {
SecureRandom providedRandom = null;
if (forSigning) {
if (param instanceof ParametersWithRandom) {
ParametersWithRandom rParam = (ParametersWithRandom) param;
this.key = (ECPrivateKeyParameters) rParam.getParameters();
providedRandom = rParam.getRandom();
} else {
this.key = (ECPrivateKeyParameters) param;
}
} else {
this.key = (ECPublicKeyParameters) param;
}
this.random = initSecureRandom(forSigning && !kCalculator.isDeterministic(), providedRandom);
}
// 5.3 pg 28
/**
* generate a signature for the given message using the key we were
* initialised with. For conventional DSA the message should be a SHA-1
* hash of the message of interest.
*
* @param message the message that will be verified later.
*/
public BigInteger[] generateSignature(
byte[] message) {
ECDomainParameters ec = key.getParameters();
BigInteger n = ec.getN();
BigInteger e = calculateE(n, message);
BigInteger d = ((ECPrivateKeyParameters) key).getD();
int nonce = 1;
BigInteger r, s;
while (true) {
kCalculator.init(n, d, message);
ECMultiplier basePointMultiplier = createBasePointMultiplier();
// 5.3.2
do // generate s
{
BigInteger k = BigInteger.ZERO;
do // generate r
{
k = kCalculator.nextK();
for (int i = 0; i < nonce; i++) {
k = kCalculator.nextK();
}
ECPoint p = basePointMultiplier.multiply(ec.getG(), k).normalize();
// 5.3.3
r = p.getAffineXCoord().toBigInteger().mod(n);
}
while (r.equals(ZERO));
// Compute s = (k^-1)*(h + Kx*privkey)
s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n);
}
while (s.equals(ZERO));
byte[] der = new ECKey.ECDSASignature(r, s).toCanonicalised().encodeToDER();
int lenR = der[3];
int lenS = der[5 + lenR];
if (lenR == 32 && lenS == 32) {
break;
}
nonce++;
}
return new BigInteger[]{r, s};
}
// 5.4 pg 29
/**
* return true if the value r and s represent a DSA signature for
* the passed in message (for standard DSA the message should be
* a SHA-1 hash of the real message to be verified).
*/
public boolean verifySignature(
byte[] message,
BigInteger r,
BigInteger s) {
ECDomainParameters ec = key.getParameters();
BigInteger n = ec.getN();
BigInteger e = calculateE(n, message);
// r in the range [1,n-1]
if (r.compareTo(ONE) < 0 || r.compareTo(n) >= 0) {
return false;
}
// s in the range [1,n-1]
if (s.compareTo(ONE) < 0 || s.compareTo(n) >= 0) {
return false;
}
BigInteger c = s.modInverse(n);
BigInteger u1 = e.multiply(c).mod(n);
BigInteger u2 = r.multiply(c).mod(n);
ECPoint G = ec.getG();
ECPoint Q = ((ECPublicKeyParameters) key).getQ();
ECPoint point = ECAlgorithms.sumOfTwoMultiplies(G, u1, Q, u2).normalize();
// components must be bogus.
if (point.isInfinity()) {
return false;
}
BigInteger v = point.getAffineXCoord().toBigInteger().mod(n);
return v.equals(r);
}
protected BigInteger calculateE(BigInteger n, byte[] message) {
int log2n = n.bitLength();
int messageBitLength = message.length * 8;
BigInteger e = new BigInteger(1, message);
if (log2n < messageBitLength) {
e = e.shiftRight(messageBitLength - log2n);
}
return e;
}
protected ECMultiplier createBasePointMultiplier() {
return new FixedPointCombMultiplier();
}
protected SecureRandom initSecureRandom(boolean needed, SecureRandom provided) {
return !needed ? null : (provided != null) ? provided : new SecureRandom();
}
}
| 5,241 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
FileTransaction.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/transaction/FileTransaction.java | package org.consenlabs.tokencore.wallet.transaction;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.HexUtil;
import com.filecoinj.crypto.ECKey;
import com.filecoinj.handler.TransactionHandler;
import com.filecoinj.model.Transaction;
import org.consenlabs.tokencore.wallet.Wallet;
import org.consenlabs.tokencore.wallet.model.Messages;
import org.consenlabs.tokencore.wallet.model.TokenException;
public class FileTransaction implements TransactionSigner {
private String from;
private String to;
private long amount;
private long nonce;
private String gasPremium;
private long gasLimit;
private String gasFeeCap;
private final static long DUST_THRESHOLD = 0;
public FileTransaction(String from, String to, long amount) {
this.from = from;
this.to = to;
this.amount = amount;
if (amount < DUST_THRESHOLD) {
throw new TokenException(Messages.AMOUNT_LESS_THAN_MINIMUM);
}
}
@Override
public TxSignResult signTransaction(String chainId, String password, Wallet wallet) {
try {
String hexPrivateKey = wallet.exportPrivateKey(password);
Transaction transaction = Transaction.builder()
.from(from)
.to(to)
.gasFeeCap(gasFeeCap)
.gasLimit(gasLimit)
.gasPremium(gasPremium)
.method(0L)
.nonce(nonce)
.params("")
.value(String.valueOf(amount)).build();
TransactionHandler transactionHandler = new TransactionHandler();
byte[] cidHash = transactionHandler.transactionSerialize(transaction);
String cid = HexUtil.encodeHexStr(cidHash);
ECKey ecKey = ECKey.fromPrivate(HexUtil.decodeHex(hexPrivateKey));
String sing = Base64.encode(ecKey.sign(cidHash).toByteArray());
System.out.println("cidHash: " + HexUtil.encodeHexStr(cidHash));
return new TxSignResult(sing, cid);
} catch (Exception e) {
throw new TokenException("签名失败 原因", e);
}
}
}
| 2,195 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
EOSTransaction.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/transaction/EOSTransaction.java | package org.consenlabs.tokencore.wallet.transaction;
import io.eblock.eos4j.OfflineSign;
import io.eblock.eos4j.api.vo.SignParam;
import io.eblock.eos4j.ese.Action;
import io.eblock.eos4j.ese.DataParam;
import io.eblock.eos4j.ese.DataType;
import io.eblock.eos4j.utils.ByteUtils;
import org.consenlabs.tokencore.foundation.crypto.Hash;
import org.consenlabs.tokencore.foundation.utils.ByteUtil;
import org.consenlabs.tokencore.foundation.utils.NumericUtil;
import org.consenlabs.tokencore.wallet.Wallet;
import org.consenlabs.tokencore.wallet.WalletManager;
import org.consenlabs.tokencore.wallet.keystore.V3Keystore;
import org.consenlabs.tokencore.wallet.model.TokenException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class EOSTransaction implements TransactionSigner {
private byte[] txBuf;
private List<ToSignObj> txsToSign;
private String from;
private String to;
private String quantity;
private String memo;
private SignParam signParam;
private String contractAccount;
public EOSTransaction(byte[] txBuf) {
this.txBuf = txBuf;
}
public EOSTransaction(List<ToSignObj> txsToSign) {
this.txsToSign = txsToSign;
}
public EOSTransaction(SignParam signParam,String contractAccount, String from, String to, String quantity, String memo) {
this.from = from;
this.to = to;
this.quantity = quantity;
this.memo = memo;
this.signParam = signParam;
this.contractAccount=contractAccount;
}
public TxSignResult signTransaction(String password, Wallet wallet) {
String pubKey=wallet.getKeyPathPrivates().get(0).getPublicKey();
String priKey = NumericUtil.bytesToHex(wallet.decryptPrvKeyFor(pubKey, password));
OfflineSign sign = new OfflineSign();
try {
String content = sign.transfer(signParam, priKey, contractAccount,
from, to, quantity, memo);
return new TxSignResult(content, "");
} catch (Exception e) {
throw new TokenException(String.format("签名失败 原因:%s",e.getMessage()));
}
}
@Deprecated
@Override
public TxSignResult signTransaction(String chainId, String password, Wallet wallet) {
String transactionID = NumericUtil.bytesToHex(Hash.sha256(txBuf));
txBuf = ByteUtil.concat(NumericUtil.hexToBytes(chainId), txBuf);
byte[] zeroBuf = new byte[32];
Arrays.fill(zeroBuf, (byte) 0);
txBuf = ByteUtil.concat(txBuf, zeroBuf);
String wif = wallet.exportPrivateKey(password);
String signed = EOSSign.sign(Hash.sha256(txBuf), wif);
return new TxSignResult(signed, transactionID);
}
public List<TxMultiSignResult> signTransactions(String chainId, String password, Wallet wallet) {
List<TxMultiSignResult> results = new ArrayList<>(txsToSign.size());
for (ToSignObj toSignObj : txsToSign) {
byte[] txBuf = NumericUtil.hexToBytes(toSignObj.txHex);
String transactionID = NumericUtil.bytesToHex(Hash.sha256(txBuf));
byte[] txChainIDBuf = ByteUtil.concat(NumericUtil.hexToBytes(chainId), txBuf);
byte[] zeroBuf = new byte[32];
Arrays.fill(zeroBuf, (byte) 0);
byte[] fullTxBuf = ByteUtil.concat(txChainIDBuf, zeroBuf);
byte[] hashedTx = Hash.sha256(fullTxBuf);
List<String> signatures = new ArrayList<>(toSignObj.publicKeys.size());
for (String pubKey : toSignObj.publicKeys) {
String signed;
if (wallet.getKeystore().getVersion() == V3Keystore.VERSION) {
signed = EOSSign.sign(hashedTx, wallet.exportPrivateKey(password));
} else {
signed = EOSSign.sign(hashedTx, wallet.decryptPrvKeyFor(pubKey, password));
}
signatures.add(signed);
}
TxMultiSignResult signedResult = new TxMultiSignResult(transactionID, signatures);
results.add(signedResult);
}
return results;
}
public static class ToSignObj {
private String txHex;
private List<String> publicKeys;
public String getTxHex() {
return txHex;
}
public void setTxHex(String txHex) {
this.txHex = txHex;
}
public List<String> getPublicKeys() {
return publicKeys;
}
public void setPublicKeys(List<String> publicKeys) {
this.publicKeys = publicKeys;
}
}
}
| 4,752 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
EOSCreateAccount.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/transaction/EOSCreateAccount.java | package org.consenlabs.tokencore.wallet.transaction;
import io.eblock.eos4j.OfflineSign;
import io.eblock.eos4j.api.vo.SignParam;
import org.consenlabs.tokencore.foundation.utils.NumericUtil;
import org.consenlabs.tokencore.wallet.Wallet;
import org.consenlabs.tokencore.wallet.model.TokenException;
/**
* Created by pie on 2019-03-05 23: 22.
*/
public class EOSCreateAccount implements TransactionSigner {
private Long buyRam;
private String newAccount;
private String creator;
private SignParam signParam;
private String newAccountPubKey;
public EOSCreateAccount(SignParam signParam, String creator, String newAccount, String newAccountPubKey,Long buyRam) {
this.signParam = signParam;
this.creator=creator;
this.newAccount=newAccount;
this.buyRam=buyRam;
this.newAccountPubKey=newAccountPubKey;
}
@Override
public TxSignResult signTransaction(String chainId, String password, Wallet wallet) {
String pubKey = wallet.getKeyPathPrivates().get(0).getPublicKey();
String priKey = NumericUtil.bytesToHex(wallet.decryptPrvKeyFor(pubKey, password));
OfflineSign sign = new OfflineSign();
try {
String content= sign.createAccount(signParam, priKey, creator,newAccount,newAccountPubKey,newAccountPubKey, buyRam);
return new TxSignResult(content, "");
} catch (Exception e) {
throw new TokenException(String.format("签名失败 原因:%s",e.getMessage()));
}
}
}
| 1,528 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
BitcoinTransaction.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/transaction/BitcoinTransaction.java | package org.consenlabs.tokencore.wallet.transaction;
import org.apache.commons.lang3.StringUtils;
import org.bitcoinj.core.*;
import org.bitcoinj.crypto.ChildNumber;
import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.crypto.HDKeyDerivation;
import org.bitcoinj.crypto.TransactionSignature;
import org.bitcoinj.script.Script;
import org.bitcoinj.script.ScriptBuilder;
import org.consenlabs.tokencore.foundation.crypto.Hash;
import org.consenlabs.tokencore.foundation.utils.ByteUtil;
import org.consenlabs.tokencore.foundation.utils.MetaUtil;
import org.consenlabs.tokencore.foundation.utils.NumericUtil;
import org.consenlabs.tokencore.wallet.Wallet;
import org.consenlabs.tokencore.wallet.model.Messages;
import org.consenlabs.tokencore.wallet.model.Metadata;
import org.consenlabs.tokencore.wallet.model.MultiTo;
import org.consenlabs.tokencore.wallet.model.TokenException;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public class BitcoinTransaction implements TransactionSigner {
private String to;
private List<MultiTo> multiToList;
private long multiToAmount;
private long amount;
private List<UTXO> outputs;
private String memo;
private long fee;
private int changeIdx;
private long locktime = 0;
private Address changeAddress;
private NetworkParameters network;
private List<BigInteger> prvKeys;
// 2730 sat
private final static long DUST_THRESHOLD = 2730;
public BitcoinTransaction(String to, int changeIdx, long amount, long fee, ArrayList<UTXO> outputs) {
this.to = to;
this.amount = amount;
this.fee = fee;
this.outputs = outputs;
this.changeIdx = changeIdx;
if (amount < DUST_THRESHOLD) {
throw new TokenException(Messages.AMOUNT_LESS_THAN_MINIMUM);
}
}
public BitcoinTransaction(List<MultiTo> multiToList, int changeIdx, long fee, ArrayList<UTXO> outputs) {
this.multiToList = multiToList;
this.fee = fee;
this.outputs = outputs;
this.changeIdx = changeIdx;
multiToList.forEach(multiTo -> {
if (multiTo.getAmount() < DUST_THRESHOLD) {
throw new TokenException(Messages.AMOUNT_LESS_THAN_MINIMUM);
}
multiToAmount += multiTo.getAmount();
});
}
@Override
public String toString() {
return "BitcoinTransaction{" +
"to='" + to + '\'' +
", amount=" + amount +
", outputs=" + outputs +
", memo='" + memo + '\'' +
", fee=" + fee +
", changeIdx=" + changeIdx +
'}';
}
public long getMultiToAmount() {
return multiToAmount;
}
public void setMultiToAmount(long multiToAmount) {
this.multiToAmount = multiToAmount;
}
public List<MultiTo> getMultiToList() {
return multiToList;
}
public void setMultiToList(List<MultiTo> multiToList) {
this.multiToList = multiToList;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public long getAmount() {
return amount;
}
public void setAmount(long amount) {
this.amount = amount;
}
public List<UTXO> getOutputs() {
return outputs;
}
public void setOutputs(List<UTXO> outputs) {
this.outputs = outputs;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public long getFee() {
return fee;
}
public void setFee(long fee) {
this.fee = fee;
}
public int getChangeIdx() {
return changeIdx;
}
public void setChangeIdx(int changeIdx) {
this.changeIdx = changeIdx;
}
public static class UTXO {
public UTXO() {
}
private String txHash;
private int vout;
private long amount;
private String address;
private String scriptPubKey;
private String derivedPath;
private long sequence = 4294967295L;
@Override
public String toString() {
return "UTXO{" +
"txHash='" + txHash + '\'' +
", vout=" + vout +
", amount=" + amount +
", address='" + address + '\'' +
", scriptPubKey='" + scriptPubKey + '\'' +
", derivedPath='" + derivedPath + '\'' +
", sequence=" + sequence +
'}';
}
public UTXO(String txHash, int vout, long amount, String address, String scriptPubKey, String derivedPath) {
this.txHash = txHash;
this.vout = vout;
this.amount = amount;
this.address = address;
this.scriptPubKey = scriptPubKey;
this.derivedPath = derivedPath;
}
public UTXO(String txHash, int vout, long amount, String address, String scriptPubKey, String derivedPath, long sequence) {
this.txHash = txHash;
this.vout = vout;
this.amount = amount;
this.address = address;
this.scriptPubKey = scriptPubKey;
this.derivedPath = derivedPath;
this.sequence = sequence;
}
public int getVout() {
return vout;
}
public void setVout(int vout) {
this.vout = vout;
}
public long getAmount() {
return amount;
}
public void setAmount(long amount) {
this.amount = amount;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTxHash() {
return txHash;
}
public void setTxHash(String txHash) {
this.txHash = txHash;
}
public String getScriptPubKey() {
return scriptPubKey;
}
public void setScriptPubKey(String scriptPubKey) {
this.scriptPubKey = scriptPubKey;
}
public String getDerivedPath() {
return derivedPath;
}
public void setDerivedPath(String derivedPath) {
this.derivedPath = derivedPath;
}
public long getSequence() {
return sequence;
}
public void setSequence(long sequence) {
this.sequence = sequence;
}
}
public TxSignResult signTransaction(String chainID, String password, Wallet wallet) {
collectPrvKeysAndAddress(Metadata.NONE, password, wallet);
Transaction tran = new Transaction(network);
long totalAmount = 0L;
for (UTXO output : getOutputs()) {
totalAmount += output.getAmount();
}
if (totalAmount < getAmount()) {
throw new TokenException(Messages.INSUFFICIENT_FUNDS);
}
//add send to output
tran.addOutput(Coin.valueOf(getAmount()), Address.fromBase58(network, getTo()));
//add change output
long changeAmount = totalAmount - (getAmount() + getFee());
if (changeAmount >= DUST_THRESHOLD) {
tran.addOutput(Coin.valueOf(changeAmount), changeAddress);
}
for (UTXO output : getOutputs()) {
tran.addInput(Sha256Hash.wrap(output.getTxHash()), output.getVout(), new Script(NumericUtil.hexToBytes(output.getScriptPubKey())));
}
for (int i = 0; i < getOutputs().size(); i++) {
UTXO output = getOutputs().get(i);
BigInteger privateKey = wallet.getMetadata().getSource().equals(Metadata.FROM_WIF) ? prvKeys.get(0) : prvKeys.get(i);
ECKey ecKey;
if (output.getAddress().equals(ECKey.fromPrivate(privateKey).toAddress(network).toBase58())) {
ecKey = ECKey.fromPrivate(privateKey);
} else if (output.getAddress().equals(ECKey.fromPrivate(privateKey, false).toAddress(network).toBase58())) {
ecKey = ECKey.fromPrivate(privateKey, false);
} else {
throw new TokenException(Messages.CAN_NOT_FOUND_PRIVATE_KEY);
}
TransactionInput transactionInput = tran.getInput(i);
Script scriptPubKey = ScriptBuilder.createOutputScript(Address.fromBase58(network, output.getAddress()));
Sha256Hash hash = tran.hashForSignature(i, scriptPubKey, Transaction.SigHash.ALL, false);
ECKey.ECDSASignature ecSig = ecKey.sign(hash);
TransactionSignature txSig = new TransactionSignature(ecSig, Transaction.SigHash.ALL, false);
if (scriptPubKey.isSentToRawPubKey()) {
transactionInput.setScriptSig(ScriptBuilder.createInputScript(txSig));
} else {
if (!scriptPubKey.isSentToAddress()) {
throw new TokenException(Messages.UNSUPPORT_SEND_TARGET);
}
transactionInput.setScriptSig(ScriptBuilder.createInputScript(txSig, ecKey));
}
}
String signedHex = NumericUtil.bytesToHex(tran.bitcoinSerialize());
String txHash = NumericUtil.beBigEndianHex(Hash.sha256(Hash.sha256(signedHex)));
return new TxSignResult(signedHex, txHash);
}
public TxSignResult signUsdtTransaction(String chainID, String password, Wallet wallet) {
collectPrvKeysAndAddress(Metadata.NONE, password, wallet);
Transaction tran = new Transaction(network);
long totalAmount = 0L;
long needAmount = 546L;
for (UTXO output : getOutputs()) {
totalAmount += output.getAmount();
}
if (totalAmount < needAmount) {
throw new TokenException(Messages.INSUFFICIENT_FUNDS);
}
//add change output
long changeAmount = totalAmount - (needAmount + getFee());
if (changeAmount >= DUST_THRESHOLD) {
tran.addOutput(Coin.valueOf(changeAmount), changeAddress);
}
String usdtHex = "6a146f6d6e69" + String.format("%016x", 31) + String.format("%016x", amount);
tran.addOutput(Coin.valueOf(0L), new Script(Utils.HEX.decode(usdtHex)));
//add send to output
tran.addOutput(Coin.valueOf(needAmount), Address.fromBase58(network, getTo()));
for (UTXO output : getOutputs()) {
tran.addInput(Sha256Hash.wrap(output.getTxHash()), output.getVout(), new Script(NumericUtil.hexToBytes(output.getScriptPubKey())));
}
for (int i = 0; i < getOutputs().size(); i++) {
UTXO output = getOutputs().get(i);
BigInteger privateKey = wallet.getMetadata().getSource().equals(Metadata.FROM_WIF) ? prvKeys.get(0) : prvKeys.get(i);
ECKey ecKey;
if (output.getAddress().equals(ECKey.fromPrivate(privateKey).toAddress(network).toBase58())) {
ecKey = ECKey.fromPrivate(privateKey);
} else if (output.getAddress().equals(ECKey.fromPrivate(privateKey, false).toAddress(network).toBase58())) {
ecKey = ECKey.fromPrivate(privateKey, false);
} else {
throw new TokenException(Messages.CAN_NOT_FOUND_PRIVATE_KEY);
}
TransactionInput transactionInput = tran.getInput(i);
Script scriptPubKey = ScriptBuilder.createOutputScript(Address.fromBase58(network, output.getAddress()));
Sha256Hash hash = tran.hashForSignature(i, scriptPubKey, Transaction.SigHash.ALL, false);
ECKey.ECDSASignature ecSig = ecKey.sign(hash);
TransactionSignature txSig = new TransactionSignature(ecSig, Transaction.SigHash.ALL, false);
if (scriptPubKey.isSentToRawPubKey()) {
transactionInput.setScriptSig(ScriptBuilder.createInputScript(txSig));
} else {
if (!scriptPubKey.isSentToAddress()) {
throw new TokenException(Messages.UNSUPPORT_SEND_TARGET);
}
transactionInput.setScriptSig(ScriptBuilder.createInputScript(txSig, ecKey));
}
}
String signedHex = NumericUtil.bytesToHex(tran.bitcoinSerialize());
String txHash = NumericUtil.beBigEndianHex(Hash.sha256(Hash.sha256(signedHex)));
return new TxSignResult(signedHex, txHash);
}
//这个可以增加手续费地址,在同一笔utxo里面执行交易
public TxSignResult signUsdtCollectTransaction(String chainID, String password, Wallet wallet, Wallet feeProviderWallet, List<UTXO> feeProviderUtxos) {
int startIdx = outputs.size();
outputs.addAll(feeProviderUtxos);
collectPrvKeysAndAddress(Metadata.NONE, password, wallet);
BigInteger feeProviderPrvKey = getPrvKeysByAddress(Metadata.NONE, password, feeProviderWallet, 0, 0);
for (int i = startIdx; i < outputs.size(); i++) {
prvKeys.set(i, feeProviderPrvKey);
}
Transaction tran = new Transaction(network);
long totalAmount = 0L;
long needAmount = 546L;
for (UTXO output : getOutputs()) {
totalAmount += output.getAmount();
}
if (totalAmount < needAmount) {
throw new TokenException(Messages.INSUFFICIENT_FUNDS);
}
//归零地址指向手续费提供方
changeAddress = Address.fromBase58(network, feeProviderWallet.getAddress());
//add change output
long changeAmount = totalAmount - (needAmount + getFee());
if (changeAmount >= DUST_THRESHOLD) {
tran.addOutput(Coin.valueOf(changeAmount), changeAddress);
}
String usdtHex = "6a146f6d6e69" + String.format("%016x", 31) + String.format("%016x", amount);
tran.addOutput(Coin.valueOf(0L), new Script(Utils.HEX.decode(usdtHex)));
//add send to output
tran.addOutput(Coin.valueOf(needAmount), Address.fromBase58(network, getTo()));
for (UTXO output : getOutputs()) {
tran.addInput(Sha256Hash.wrap(output.getTxHash()), output.getVout(), new Script(NumericUtil.hexToBytes(output.getScriptPubKey())));
}
for (int i = 0; i < getOutputs().size(); i++) {
UTXO output = getOutputs().get(i);
BigInteger privateKey = wallet.getMetadata().getSource().equals(Metadata.FROM_WIF) ? prvKeys.get(0) : prvKeys.get(i);
ECKey ecKey;
if (output.getAddress().equals(ECKey.fromPrivate(privateKey).toAddress(network).toBase58())) {
ecKey = ECKey.fromPrivate(privateKey);
} else if (output.getAddress().equals(ECKey.fromPrivate(privateKey, false).toAddress(network).toBase58())) {
ecKey = ECKey.fromPrivate(privateKey, false);
} else {
throw new TokenException(Messages.CAN_NOT_FOUND_PRIVATE_KEY);
}
TransactionInput transactionInput = tran.getInput(i);
Script scriptPubKey = ScriptBuilder.createOutputScript(Address.fromBase58(network, output.getAddress()));
Sha256Hash hash = tran.hashForSignature(i, scriptPubKey, Transaction.SigHash.ALL, false);
ECKey.ECDSASignature ecSig = ecKey.sign(hash);
TransactionSignature txSig = new TransactionSignature(ecSig, Transaction.SigHash.ALL, false);
if (scriptPubKey.isSentToRawPubKey()) {
transactionInput.setScriptSig(ScriptBuilder.createInputScript(txSig));
} else {
if (!scriptPubKey.isSentToAddress()) {
throw new TokenException(Messages.UNSUPPORT_SEND_TARGET);
}
transactionInput.setScriptSig(ScriptBuilder.createInputScript(txSig, ecKey));
}
}
String signedHex = NumericUtil.bytesToHex(tran.bitcoinSerialize());
String txHash = NumericUtil.beBigEndianHex(Hash.sha256(Hash.sha256(signedHex)));
return new TxSignResult(signedHex, txHash);
}
public TxSignResult signUsdtSegWitTransaction(String chainId, String password, Wallet wallet) {
collectPrvKeysAndAddress(Metadata.P2WPKH, password, wallet);
long totalAmount = 0L;
boolean hasChange = false;
for (UTXO output : getOutputs()) {
totalAmount += output.getAmount();
}
long needAmount = 546L;
if (totalAmount < needAmount) {
throw new TokenException(Messages.INSUFFICIENT_FUNDS);
}
long changeAmount = totalAmount - (needAmount + getFee());
Address toAddress = Address.fromBase58(network, to);
byte[] targetScriptPubKey;
if (toAddress.isP2SHAddress()) {
targetScriptPubKey = ScriptBuilder.createP2SHOutputScript(toAddress.getHash160()).getProgram();
} else {
targetScriptPubKey = ScriptBuilder.createOutputScript(toAddress).getProgram();
}
byte[] changeScriptPubKey = ScriptBuilder.createP2SHOutputScript(changeAddress.getHash160()).getProgram();
byte[] hashPrevouts;
byte[] hashOutputs;
byte[] hashSequence;
try {
// calc hash prevouts
UnsafeByteArrayOutputStream stream = new UnsafeByteArrayOutputStream();
for (UTXO utxo : getOutputs()) {
TransactionOutPoint outPoint = new TransactionOutPoint(this.network, utxo.vout, Sha256Hash.wrap(utxo.txHash));
outPoint.bitcoinSerialize(stream);
}
hashPrevouts = Sha256Hash.hashTwice(stream.toByteArray());
// calc hash outputs
stream = new UnsafeByteArrayOutputStream();
if (changeAmount >= DUST_THRESHOLD) {
hasChange = true;
TransactionOutput changeOutput = new TransactionOutput(this.network, null, Coin.valueOf(changeAmount), changeAddress);
changeOutput.bitcoinSerialize(stream);
}
TransactionOutput targetOutput = new TransactionOutput(this.network, null, Coin.valueOf(needAmount), toAddress);
targetOutput.bitcoinSerialize(stream);
String usdtHex = "6a146f6d6e69" + String.format("%016x", 31) + String.format("%016x", amount);
TransactionOutput usdtOutput = new TransactionOutput(this.network, null, Coin.valueOf(0L), new Script(Utils.HEX.decode(usdtHex)).getProgram());
usdtOutput.bitcoinSerialize(stream);
//
// Utils.uint64ToByteStreamLE(BigInteger.valueOf(amount), stream);
// stream.write(new VarInt(targetScriptPubKey.length).encode());
// stream.write(targetScriptPubKey);
// Utils.uint64ToByteStreamLE(BigInteger.valueOf(changeAmount), stream);
// stream.write(new VarInt(changeScriptPubKey.length).encode());
// stream.write(changeScriptPubKey);
hashOutputs = Sha256Hash.hashTwice(stream.toByteArray());
// calc hash sequence
stream = new UnsafeByteArrayOutputStream();
for (UTXO utxo : getOutputs()) {
Utils.uint32ToByteStreamLE(utxo.getSequence(), stream);
}
hashSequence = Sha256Hash.hashTwice(stream.toByteArray());
// calc witnesses and redemScripts
List<byte[]> witnesses = new ArrayList<>();
List<String> redeemScripts = new ArrayList<>();
for (int i = 0; i < getOutputs().size(); i++) {
UTXO utxo = getOutputs().get(i);
BigInteger prvKey = Metadata.FROM_WIF.equals(wallet.getMetadata().getSource()) ? prvKeys.get(0) : prvKeys.get(i);
ECKey key = ECKey.fromPrivate(prvKey, true);
String redeemScript = String.format("0014%s", NumericUtil.bytesToHex(key.getPubKeyHash()));
redeemScripts.add(redeemScript);
// calc outpoint
stream = new UnsafeByteArrayOutputStream();
TransactionOutPoint txOutPoint = new TransactionOutPoint(this.network, utxo.vout, Sha256Hash.wrap(utxo.txHash));
txOutPoint.bitcoinSerialize(stream);
byte[] outpoint = stream.toByteArray();
// calc scriptCode
byte[] scriptCode = NumericUtil.hexToBytes(String.format("0x1976a914%s88ac", NumericUtil.bytesToHex(key.getPubKeyHash())));
// before sign
stream = new UnsafeByteArrayOutputStream();
Utils.uint32ToByteStreamLE(2L, stream);
stream.write(hashPrevouts);
stream.write(hashSequence);
stream.write(outpoint);
stream.write(scriptCode);
Utils.uint64ToByteStreamLE(BigInteger.valueOf(utxo.getAmount()), stream);
Utils.uint32ToByteStreamLE(utxo.getSequence(), stream);
stream.write(hashOutputs);
Utils.uint32ToByteStreamLE(locktime, stream);
// hashType 1 = all
Utils.uint32ToByteStreamLE(1L, stream);
byte[] hashPreimage = stream.toByteArray();
byte[] sigHash = Sha256Hash.hashTwice(hashPreimage);
ECKey.ECDSASignature signature = key.sign(Sha256Hash.wrap(sigHash));
byte hashType = 0x01;
// witnesses
byte[] sig = ByteUtil.concat(signature.encodeToDER(), new byte[]{hashType});
witnesses.add(sig);
}
// the second stream is used to calc the traditional txhash
UnsafeByteArrayOutputStream[] serialStreams = new UnsafeByteArrayOutputStream[]{
new UnsafeByteArrayOutputStream(), new UnsafeByteArrayOutputStream()
};
for (int idx = 0; idx < 2; idx++) {
stream = serialStreams[idx];
Utils.uint32ToByteStreamLE(2L, stream); // version
if (idx == 0) {
stream.write(0x00); // maker
stream.write(0x01); // flag
}
// inputs
stream.write(new VarInt(getOutputs().size()).encode());
for (int i = 0; i < getOutputs().size(); i++) {
UTXO utxo = getOutputs().get(i);
stream.write(NumericUtil.reverseBytes(NumericUtil.hexToBytes(utxo.txHash)));
Utils.uint32ToByteStreamLE(utxo.getVout(), stream);
// the length of byte array that follows, and this length is used by OP_PUSHDATA1
stream.write(0x17);
// the length of byte array that follows, and this length is used by cutting array
stream.write(0x16);
stream.write(NumericUtil.hexToBytes(redeemScripts.get(i)));
Utils.uint32ToByteStreamLE(utxo.getSequence(), stream);
}
// outputs
// outputs size
int outputSize = hasChange ? 3 : 2;
stream.write(new VarInt(outputSize).encode());
if (hasChange) {
Utils.uint64ToByteStreamLE(BigInteger.valueOf(changeAmount), stream);
stream.write(new VarInt(changeScriptPubKey.length).encode());
stream.write(changeScriptPubKey);
}
Utils.uint64ToByteStreamLE(BigInteger.valueOf(needAmount), stream);
stream.write(new VarInt(targetScriptPubKey.length).encode());
stream.write(targetScriptPubKey);
Utils.uint64ToByteStreamLE(BigInteger.valueOf(0L), stream);
stream.write(new VarInt(new Script(Utils.HEX.decode(usdtHex)).getProgram().length).encode());
stream.write(new Script(Utils.HEX.decode(usdtHex)).getProgram());
// the first stream is used to calc the segwit hash
if (idx == 0) {
for (int i = 0; i < witnesses.size(); i++) {
BigInteger prvKey = Metadata.FROM_WIF.equals(wallet.getMetadata().getSource()) ? prvKeys.get(0) : prvKeys.get(i);
ECKey ecKey = ECKey.fromPrivate(prvKey);
byte[] wit = witnesses.get(i);
stream.write(new VarInt(2).encode());
stream.write(new VarInt(wit.length).encode());
stream.write(wit);
stream.write(new VarInt(ecKey.getPubKey().length).encode());
stream.write(ecKey.getPubKey());
}
}
Utils.uint32ToByteStreamLE(locktime, stream);
}
byte[] signed = serialStreams[0].toByteArray();
String signedHex = NumericUtil.bytesToHex(signed);
String wtxID = NumericUtil.bytesToHex(Sha256Hash.hashTwice(signed));
wtxID = NumericUtil.beBigEndianHex(wtxID);
String txHash = NumericUtil.bytesToHex(Sha256Hash.hashTwice(serialStreams[1].toByteArray()));
txHash = NumericUtil.beBigEndianHex(txHash);
return new TxSignResult(signedHex, txHash, wtxID);
} catch (IOException ex) {
throw new TokenException("OutputStream error");
}
}
public TxSignResult signSegWitTransaction(String chainId, String password, Wallet wallet) {
collectPrvKeysAndAddress(Metadata.P2WPKH, password, wallet);
long totalAmount = 0L;
boolean hasChange = false;
for (UTXO output : getOutputs()) {
totalAmount += output.getAmount();
}
if (totalAmount < getAmount()) {
throw new TokenException(Messages.INSUFFICIENT_FUNDS);
}
long changeAmount = totalAmount - (getAmount() + getFee());
Address toAddress = Address.fromBase58(network, to);
byte[] targetScriptPubKey;
if (toAddress.isP2SHAddress()) {
targetScriptPubKey = ScriptBuilder.createP2SHOutputScript(toAddress.getHash160()).getProgram();
} else {
targetScriptPubKey = ScriptBuilder.createOutputScript(toAddress).getProgram();
}
byte[] changeScriptPubKey = ScriptBuilder.createP2SHOutputScript(changeAddress.getHash160()).getProgram();
byte[] hashPrevouts;
byte[] hashOutputs;
byte[] hashSequence;
try {
// calc hash prevouts
UnsafeByteArrayOutputStream stream = new UnsafeByteArrayOutputStream();
for (UTXO utxo : getOutputs()) {
TransactionOutPoint outPoint = new TransactionOutPoint(this.network, utxo.vout, Sha256Hash.wrap(utxo.txHash));
outPoint.bitcoinSerialize(stream);
}
hashPrevouts = Sha256Hash.hashTwice(stream.toByteArray());
// calc hash outputs
stream = new UnsafeByteArrayOutputStream();
TransactionOutput targetOutput = new TransactionOutput(this.network, null, Coin.valueOf(amount), toAddress);
targetOutput.bitcoinSerialize(stream);
if (changeAmount >= DUST_THRESHOLD) {
hasChange = true;
TransactionOutput changeOutput = new TransactionOutput(this.network, null, Coin.valueOf(changeAmount), changeAddress);
changeOutput.bitcoinSerialize(stream);
}
//
// Utils.uint64ToByteStreamLE(BigInteger.valueOf(amount), stream);
// stream.write(new VarInt(targetScriptPubKey.length).encode());
// stream.write(targetScriptPubKey);
// Utils.uint64ToByteStreamLE(BigInteger.valueOf(changeAmount), stream);
// stream.write(new VarInt(changeScriptPubKey.length).encode());
// stream.write(changeScriptPubKey);
hashOutputs = Sha256Hash.hashTwice(stream.toByteArray());
// calc hash sequence
stream = new UnsafeByteArrayOutputStream();
for (UTXO utxo : getOutputs()) {
Utils.uint32ToByteStreamLE(utxo.getSequence(), stream);
}
hashSequence = Sha256Hash.hashTwice(stream.toByteArray());
// calc witnesses and redemScripts
List<byte[]> witnesses = new ArrayList<>();
List<String> redeemScripts = new ArrayList<>();
for (int i = 0; i < getOutputs().size(); i++) {
UTXO utxo = getOutputs().get(i);
BigInteger prvKey = Metadata.FROM_WIF.equals(wallet.getMetadata().getSource()) ? prvKeys.get(0) : prvKeys.get(i);
ECKey key = ECKey.fromPrivate(prvKey, true);
String redeemScript = String.format("0014%s", NumericUtil.bytesToHex(key.getPubKeyHash()));
redeemScripts.add(redeemScript);
// calc outpoint
stream = new UnsafeByteArrayOutputStream();
TransactionOutPoint txOutPoint = new TransactionOutPoint(this.network, utxo.vout, Sha256Hash.wrap(utxo.txHash));
txOutPoint.bitcoinSerialize(stream);
byte[] outpoint = stream.toByteArray();
// calc scriptCode
byte[] scriptCode = NumericUtil.hexToBytes(String.format("0x1976a914%s88ac", NumericUtil.bytesToHex(key.getPubKeyHash())));
// before sign
stream = new UnsafeByteArrayOutputStream();
Utils.uint32ToByteStreamLE(2L, stream);
stream.write(hashPrevouts);
stream.write(hashSequence);
stream.write(outpoint);
stream.write(scriptCode);
Utils.uint64ToByteStreamLE(BigInteger.valueOf(utxo.getAmount()), stream);
Utils.uint32ToByteStreamLE(utxo.getSequence(), stream);
stream.write(hashOutputs);
Utils.uint32ToByteStreamLE(locktime, stream);
// hashType 1 = all
Utils.uint32ToByteStreamLE(1L, stream);
byte[] hashPreimage = stream.toByteArray();
byte[] sigHash = Sha256Hash.hashTwice(hashPreimage);
ECKey.ECDSASignature signature = key.sign(Sha256Hash.wrap(sigHash));
byte hashType = 0x01;
// witnesses
byte[] sig = ByteUtil.concat(signature.encodeToDER(), new byte[]{hashType});
witnesses.add(sig);
}
// the second stream is used to calc the traditional txhash
UnsafeByteArrayOutputStream[] serialStreams = new UnsafeByteArrayOutputStream[]{
new UnsafeByteArrayOutputStream(), new UnsafeByteArrayOutputStream()
};
for (int idx = 0; idx < 2; idx++) {
stream = serialStreams[idx];
Utils.uint32ToByteStreamLE(2L, stream); // version
if (idx == 0) {
stream.write(0x00); // maker
stream.write(0x01); // flag
}
// inputs
stream.write(new VarInt(getOutputs().size()).encode());
for (int i = 0; i < getOutputs().size(); i++) {
UTXO utxo = getOutputs().get(i);
stream.write(NumericUtil.reverseBytes(NumericUtil.hexToBytes(utxo.txHash)));
Utils.uint32ToByteStreamLE(utxo.getVout(), stream);
// the length of byte array that follows, and this length is used by OP_PUSHDATA1
stream.write(0x17);
// the length of byte array that follows, and this length is used by cutting array
stream.write(0x16);
stream.write(NumericUtil.hexToBytes(redeemScripts.get(i)));
Utils.uint32ToByteStreamLE(utxo.getSequence(), stream);
}
// outputs
// outputs size
int outputSize = hasChange ? 2 : 1;
stream.write(new VarInt(outputSize).encode());
Utils.uint64ToByteStreamLE(BigInteger.valueOf(amount), stream);
stream.write(new VarInt(targetScriptPubKey.length).encode());
stream.write(targetScriptPubKey);
if (hasChange) {
Utils.uint64ToByteStreamLE(BigInteger.valueOf(changeAmount), stream);
stream.write(new VarInt(changeScriptPubKey.length).encode());
stream.write(changeScriptPubKey);
}
// the first stream is used to calc the segwit hash
if (idx == 0) {
for (int i = 0; i < witnesses.size(); i++) {
BigInteger prvKey = Metadata.FROM_WIF.equals(wallet.getMetadata().getSource()) ? prvKeys.get(0) : prvKeys.get(i);
ECKey ecKey = ECKey.fromPrivate(prvKey);
byte[] wit = witnesses.get(i);
stream.write(new VarInt(2).encode());
stream.write(new VarInt(wit.length).encode());
stream.write(wit);
stream.write(new VarInt(ecKey.getPubKey().length).encode());
stream.write(ecKey.getPubKey());
}
}
Utils.uint32ToByteStreamLE(locktime, stream);
}
byte[] signed = serialStreams[0].toByteArray();
String signedHex = NumericUtil.bytesToHex(signed);
String wtxID = NumericUtil.bytesToHex(Sha256Hash.hashTwice(signed));
wtxID = NumericUtil.beBigEndianHex(wtxID);
String txHash = NumericUtil.bytesToHex(Sha256Hash.hashTwice(serialStreams[1].toByteArray()));
txHash = NumericUtil.beBigEndianHex(txHash);
return new TxSignResult(signedHex, txHash, wtxID);
} catch (IOException ex) {
throw new TokenException("OutputStream error");
}
}
//多笔对多笔交易
public TxSignResult signMultiTransaction(String chainID, String password, List<Wallet> wallets) {
HashMap<String, ECKey> ecKeyMap = new HashMap<>();
wallets.forEach(wallet -> {
BigInteger prvKey = getPrvKeysByAddress(Metadata.NONE, password, wallet, 0, 0);
ECKey ecKey = ECKey.fromPrivate(prvKey);
String address = ecKey.toAddress(network).toBase58();
ecKeyMap.put(address, ecKey);
});
Transaction tran = new Transaction(network);
long totalAmount = 0L;
for (UTXO output : getOutputs()) {
totalAmount += output.getAmount();
}
if (totalAmount < getMultiToAmount()) {
throw new TokenException(Messages.INSUFFICIENT_FUNDS);
}
//add send to output list
getMultiToList().forEach(multiTo -> {
tran.addOutput(Coin.valueOf(multiTo.getAmount()), Address.fromBase58(network, multiTo.getTo()));
});
//add change output
long changeAmount = totalAmount - (getMultiToAmount() + getFee());
if (changeAmount >= DUST_THRESHOLD) {
tran.addOutput(Coin.valueOf(changeAmount), changeAddress);
}
for (UTXO output : getOutputs()) {
tran.addInput(Sha256Hash.wrap(output.getTxHash()), output.getVout(), new Script(NumericUtil.hexToBytes(output.getScriptPubKey())));
}
for (int i = 0; i < getOutputs().size(); i++) {
UTXO output = getOutputs().get(i);
ECKey ecKey = ecKeyMap.get(output.getAddress());
if (ecKey == null) throw new TokenException(Messages.CAN_NOT_FOUND_PRIVATE_KEY);
TransactionInput transactionInput = tran.getInput(i);
Script scriptPubKey = ScriptBuilder.createOutputScript(Address.fromBase58(network, output.getAddress()));
Sha256Hash hash = tran.hashForSignature(i, scriptPubKey, Transaction.SigHash.ALL, false);
ECKey.ECDSASignature ecSig = ecKey.sign(hash);
TransactionSignature txSig = new TransactionSignature(ecSig, Transaction.SigHash.ALL, false);
if (scriptPubKey.isSentToRawPubKey()) {
transactionInput.setScriptSig(ScriptBuilder.createInputScript(txSig));
} else {
if (!scriptPubKey.isSentToAddress()) {
throw new TokenException(Messages.UNSUPPORT_SEND_TARGET);
}
transactionInput.setScriptSig(ScriptBuilder.createInputScript(txSig, ecKey));
}
}
String signedHex = NumericUtil.bytesToHex(tran.bitcoinSerialize());
String txHash = NumericUtil.beBigEndianHex(Hash.sha256(Hash.sha256(signedHex)));
return new TxSignResult(signedHex, txHash);
}
private void collectPrvKeysAndAddress(String segWit, String password, Wallet wallet) {
this.network = MetaUtil.getNetWork(wallet.getMetadata());
if (wallet.getMetadata().getSource().equals(Metadata.FROM_WIF)) {
changeAddress = Address.fromBase58(network, wallet.getAddress());
BigInteger prvKey = DumpedPrivateKey.fromBase58(network, wallet.exportPrivateKey(password)).getKey().getPrivKey();
prvKeys = Collections.singletonList(prvKey);
} else {
prvKeys = new ArrayList<>(getOutputs().size());
String xprv = new String(wallet.decryptMainKey(password), Charset.forName("UTF-8"));
DeterministicKey xprvKey = DeterministicKey.deserializeB58(xprv, network);
DeterministicKey changeKey = HDKeyDerivation.deriveChildKey(xprvKey, ChildNumber.ONE);
//将找零指向自己地址
changeAddress = Address.fromBase58(network, wallet.getAddress());
// DeterministicKey indexKey = HDKeyDerivation.deriveChildKey(changeKey, new ChildNumber(getChangeIdx(), false));
// if (Metadata.P2WPKH.equals(segWit)) {
// changeAddress = new SegWitBitcoinAddressCreator(network).fromPrivateKey(indexKey);
// } else {
// changeAddress = indexKey.toAddress(network);
// }
for (UTXO output : getOutputs()) {
String derivedPath = output.getDerivedPath().trim();
String[] pathIdxs = derivedPath.replace('/', ' ').split(" ");
int accountIdx = Integer.parseInt(pathIdxs[0]);
int changeIdx = Integer.parseInt(pathIdxs[1]);
DeterministicKey accountKey = HDKeyDerivation.deriveChildKey(xprvKey, new ChildNumber(accountIdx, false));
DeterministicKey externalChangeKey = HDKeyDerivation.deriveChildKey(accountKey, new ChildNumber(changeIdx, false));
prvKeys.add(externalChangeKey.getPrivKey());
}
}
}
private BigInteger getPrvKeysByAddress(String segWit, String password, Wallet wallet, int accountIdx, int changeIdx) {
BigInteger prvKey;
this.network = MetaUtil.getNetWork(wallet.getMetadata());
if (wallet.getMetadata().getSource().equals(Metadata.FROM_WIF)) {
changeAddress = Address.fromBase58(network, wallet.getAddress());
prvKey = DumpedPrivateKey.fromBase58(network, wallet.exportPrivateKey(password)).getKey().getPrivKey();
} else {
String xprv = new String(wallet.decryptMainKey(password), Charset.forName("UTF-8"));
DeterministicKey xprvKey = DeterministicKey.deserializeB58(xprv, network);
DeterministicKey accountKey = HDKeyDerivation.deriveChildKey(xprvKey, new ChildNumber(accountIdx, false));
DeterministicKey externalChangeKey = HDKeyDerivation.deriveChildKey(accountKey, new ChildNumber(changeIdx, false));
prvKey = externalChangeKey.getPrivKey();
}
return prvKey;
}
}
| 40,833 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
TxMultiSignResult.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/transaction/TxMultiSignResult.java | package org.consenlabs.tokencore.wallet.transaction;
import java.util.List;
public class TxMultiSignResult {
public TxMultiSignResult(String txHash, List<String> signed) {
this.txHash = txHash;
this.signed = signed;
}
String txHash;
List<String> signed;
public String getTxHash() {
return txHash;
}
public void setTxHash(String txHash) {
this.txHash = txHash;
}
public List<String> getSigned() {
return signed;
}
public void setSigned(List<String> signed) {
this.signed = signed;
}
}
| 570 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
TransactionSigner.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/transaction/TransactionSigner.java | package org.consenlabs.tokencore.wallet.transaction;
import org.consenlabs.tokencore.wallet.Wallet;
public interface TransactionSigner {
TxSignResult signTransaction(String chainId, String password, Wallet wallet);
}
| 228 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
TronTransaction.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/transaction/TronTransaction.java | package org.consenlabs.tokencore.wallet.transaction;
import org.consenlabs.tokencore.wallet.Wallet;
import org.consenlabs.tokencore.wallet.model.Messages;
import org.consenlabs.tokencore.wallet.model.TokenException;
import org.spongycastle.util.encoders.Hex;
import org.tron.trident.abi.FunctionEncoder;
import org.tron.trident.abi.TypeReference;
import org.tron.trident.abi.datatypes.Address;
import org.tron.trident.abi.datatypes.Bool;
import org.tron.trident.abi.datatypes.Function;
import org.tron.trident.abi.datatypes.generated.Uint256;
import org.tron.trident.core.ApiWrapper;
import org.tron.trident.core.exceptions.IllegalException;
import org.tron.trident.crypto.SECP256K1;
import org.tron.trident.crypto.tuwenitypes.Bytes32;
import org.tron.trident.proto.Chain;
import org.tron.trident.proto.Contract;
import org.tron.trident.proto.Response;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;
public class TronTransaction implements TransactionSigner {
private final static long DUST_THRESHOLD = 0;
public TronTransaction(String from, String to, long amount) {
this.from = from;
this.to = to;
this.amount = amount;
if (amount < DUST_THRESHOLD) {
throw new TokenException(Messages.AMOUNT_LESS_THAN_MINIMUM);
}
}
public TronTransaction(String from, String to, int tokenId, long amount) {
this.from = from;
this.to = to;
this.tokenId = tokenId;
this.amount = amount;
if (amount < DUST_THRESHOLD) {
throw new TokenException(Messages.AMOUNT_LESS_THAN_MINIMUM);
}
}
public TronTransaction(String from, String to, String contractAddress, long amount) {
this.from = from;
this.to = to;
this.contractAddress = contractAddress;
this.amount = amount;
if (amount < DUST_THRESHOLD) {
throw new TokenException(Messages.AMOUNT_LESS_THAN_MINIMUM);
}
}
private String from;
private String to;
private long amount;
private int tokenId;
private String contractAddress;
ApiWrapper client = ApiWrapper.ofMainnet("");
@Override
public TxSignResult signTransaction(String chainId, String password, Wallet wallet) {
String hexPrivateKey = wallet.exportPrivateKey(password);
SECP256K1.KeyPair keyPair = SECP256K1.KeyPair.create(SECP256K1.PrivateKey.create(Bytes32.fromHexString(hexPrivateKey)));
Response.TransactionExtention txnExt;
try {
txnExt = client.transfer(from, to, amount);
Chain.Transaction signedTransaction = client.signTransaction(txnExt, keyPair);
String txid = Hex.toHexString(txnExt.getTxid().toByteArray());
return new TxSignResult(signedTransaction.toString(), txid);
} catch (IllegalException e) {
throw new TokenException("签名失败 原因", e);
}
}
public TxSignResult signTrc10Transaction(String chainId, String password, Wallet wallet) {
String hexPrivateKey = wallet.exportPrivateKey(password);
SECP256K1.KeyPair keyPair = SECP256K1.KeyPair.create(SECP256K1.PrivateKey.create(Bytes32.fromHexString(hexPrivateKey)));
Response.TransactionExtention txnExt;
try {
txnExt = client.transferTrc10(from, to, tokenId, amount);
Chain.Transaction signedTransaction = client.signTransaction(txnExt, keyPair);
String txid = Hex.toHexString(txnExt.getTxid().toByteArray());
return new TxSignResult(signedTransaction.toString(), txid);
} catch (IllegalException e) {
throw new TokenException("签名失败 原因", e);
}
}
public TxSignResult signTrc20Transaction(String chainId, String password, Wallet wallet) {
String hexPrivateKey = wallet.exportPrivateKey(password);
SECP256K1.KeyPair keyPair = SECP256K1.KeyPair.create(SECP256K1.PrivateKey.create(Bytes32.fromHexString(hexPrivateKey)));
// transfer(address,uint256) returns (bool)
Function trc20Transfer = new Function("transfer",
Arrays.asList(new Address(to),
new Uint256(BigInteger.valueOf(amount))),
Collections.singletonList(new TypeReference<Bool>() {
}));
String encodedHex = FunctionEncoder.encode(trc20Transfer);
Contract.TriggerSmartContract trigger =
Contract.TriggerSmartContract.newBuilder()
.setOwnerAddress(ApiWrapper.parseAddress(from))
.setContractAddress(ApiWrapper.parseAddress(contractAddress))
.setData(ApiWrapper.parseHex(encodedHex))
.build();
Response.TransactionExtention txnExt = client.blockingStub.triggerContract(trigger);
String txid = Hex.toHexString(txnExt.getTxid().toByteArray());
Chain.Transaction signedTxn = client.signTransaction(txnExt, keyPair);
return new TxSignResult(signedTxn.toString(), txid);
}
}
| 5,092 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
EOSKey.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/transaction/EOSKey.java | package org.consenlabs.tokencore.wallet.transaction;
import org.bitcoinj.core.AddressFormatException;
import org.bitcoinj.core.Base58;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.VersionedChecksummedBytes;
import org.consenlabs.tokencore.foundation.utils.ByteUtil;
import org.spongycastle.crypto.digests.RIPEMD160Digest;
import java.util.Arrays;
public class EOSKey extends VersionedChecksummedBytes {
protected EOSKey(String encoded) throws AddressFormatException {
super(encoded);
}
protected EOSKey(int version, byte[] bytes) {
super(version, bytes);
}
public static EOSKey fromWIF(String wif) {
return new EOSKey(wif);
}
public static EOSKey fromPrivate(byte[] prvKey) {
// EOS doesn't distinguish between mainnet and testnet.
return new EOSKey(128, prvKey);
}
public static String privateToPublicKey(byte[] prvKey) {
return new EOSKey(128, prvKey).getPublicKeyAsHex();
}
public String getPublicKeyAsHex() {
ECKey ecKey = ECKey.fromPrivate(bytes);
byte[] pubKeyData = ecKey.getPubKey();
RIPEMD160Digest digest = new RIPEMD160Digest();
digest.update(pubKeyData, 0, pubKeyData.length);
byte[] out = new byte[20];
digest.doFinal(out, 0);
byte[] checksumBytes = Arrays.copyOfRange(out, 0, 4);
pubKeyData = ByteUtil.concat(pubKeyData, checksumBytes);
return "EOS" + Base58.encode(pubKeyData);
}
public byte[] getPrivateKey() {
return bytes;
}
ECKey getECKey() {
return ECKey.fromPrivate(bytes, true);
}
}
| 1,586 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
SignatureData.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/transaction/SignatureData.java | package org.consenlabs.tokencore.wallet.transaction;
import org.consenlabs.tokencore.foundation.utils.NumericUtil;
import java.util.Arrays;
/**
* Created by xyz on 2018/3/2.
*/
public class SignatureData {
private final int v;
private final byte[] r;
private final byte[] s;
public SignatureData(int v, byte[] r, byte[] s) {
this.v = v;
this.r = r;
this.s = s;
}
public int getV() {
return v;
}
public byte[] getR() {
return r;
}
public byte[] getS() {
return s;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SignatureData that = (SignatureData) o;
if (v != that.v) {
return false;
}
if (!Arrays.equals(r, that.r)) {
return false;
}
return Arrays.equals(s, that.s);
}
@Override
public int hashCode() {
int result = v;
result = 31 * result + Arrays.hashCode(r);
result = 31 * result + Arrays.hashCode(s);
return result;
}
@Override
public String toString() {
String r = NumericUtil.bytesToHex(getR());
String s = NumericUtil.bytesToHex(getS());
return String.format("%s%s%02x", r, s, getV());
}
}
| 1,328 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
EthereumSign.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/transaction/EthereumSign.java | package org.consenlabs.tokencore.wallet.transaction;
import com.subgraph.orchid.encoders.Hex;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.Sha256Hash;
import org.consenlabs.tokencore.foundation.crypto.Hash;
import org.consenlabs.tokencore.foundation.utils.ByteUtil;
import org.consenlabs.tokencore.foundation.utils.NumericUtil;
import org.consenlabs.tokencore.wallet.address.EthereumAddressCreator;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.SignatureException;
import java.util.Arrays;
import java.util.Locale;
import static com.google.common.base.Preconditions.checkState;
/**
* Created by xyz on 2017/12/20.
*/
public class EthereumSign {
public static String personalSign(String data, byte[] prvKeyBytes) {
byte[] dataBytes = dataToBytes(data);
int msgLen = dataBytes.length;
String headerMsg = String.format(Locale.ENGLISH, "\u0019Ethereum Signed Message:\n%d", msgLen);
byte[] headerMsgBytes = headerMsg.getBytes(Charset.forName("UTF-8"));
byte[] dataToSign = ByteUtil.concat(headerMsgBytes, dataBytes);
return signMessage(dataToSign, prvKeyBytes).toString();
}
public static String sign(String data, byte[] prvKeyBytes) {
return signMessage(dataToBytes(data), prvKeyBytes).toString();
}
public static BigInteger ecRecover(String data, String signature) throws SignatureException {
byte[] msgBytes = dataToBytes(data);
signature = NumericUtil.cleanHexPrefix(signature);
byte[] r = Hex.decode(signature.substring(0, 64));
byte[] s = Hex.decode(signature.substring(64, 128));
int receiveId = Integer.valueOf(signature.substring(128), 16);
SignatureData signatureData = new SignatureData((byte) receiveId, r, s);
return signedMessageToKey(msgBytes, signatureData);
}
public static String recoverAddress(String data, String signature) {
try {
BigInteger pubKey = ecRecover(data, signature);
return new EthereumAddressCreator().fromPublicKey(pubKey);
} catch (SignatureException e) {
return "";
}
}
private static byte[] dataToBytes(String data) {
byte[] messageBytes;
if (NumericUtil.isValidHex(data)) {
messageBytes = NumericUtil.hexToBytes(data);
} else {
messageBytes = data.getBytes(Charset.forName("UTF-8"));
}
return messageBytes;
}
static SignatureData signMessage(byte[] message, byte[] prvKeyBytes) {
ECKey ecKey = ECKey.fromPrivate(prvKeyBytes);
byte[] messageHash = Hash.keccak256(message);
return signAsRecoverable(messageHash, ecKey);
}
/**
* Given an arbitrary piece of text and an Ethereum message signature encoded in bytes,
* returns the public key that was used to sign it. This can then be compared to the expected
* public key to determine if the signature was correct.
*
* @param message RLP encoded message.
* @param signatureData The message signature components
* @return the public key used to sign the message
* @throws SignatureException If the public key could not be recovered or if there was a
* signature format error.
*/
private static BigInteger signedMessageToKey(byte[] message, SignatureData signatureData) throws SignatureException {
byte[] r = signatureData.getR();
byte[] s = signatureData.getS();
checkState(r != null && r.length == 32, "r must be 32 bytes");
checkState(s != null && s.length == 32, "s must be 32 bytes");
int header = signatureData.getV() & 0xFF;
// The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
// 0x1D = second key with even y, 0x1E = second key with odd y
if (header < 27 || header > 34) {
throw new SignatureException("Header byte out of range: " + header);
}
ECKey.ECDSASignature sig = new ECKey.ECDSASignature(
new BigInteger(1, signatureData.getR()),
new BigInteger(1, signatureData.getS()));
byte[] messageHash = Hash.keccak256(message);
int recId = header - 27;
ECKey key = ECKey.recoverFromSignature(recId, sig, Sha256Hash.wrap(messageHash), false);
if (key == null) {
throw new SignatureException("Could not recover public key from signature");
}
byte[] pubKeyBytes = key.getPubKeyPoint().getEncoded(false);
return NumericUtil.bytesToBigInteger(Arrays.copyOfRange(pubKeyBytes, 1, pubKeyBytes.length));
}
public static SignatureData signAsRecoverable(byte[] value, ECKey ecKey) {
ECKey.ECDSASignature sig = ecKey.sign(Sha256Hash.wrap(value));
// Now we have to work backwards to figure out the recId needed to recover the signature.
int recId = -1;
for (int i = 0; i < 4; i++) {
ECKey recoverKey = ECKey.recoverFromSignature(i, sig, Sha256Hash.wrap(value), false);
if (recoverKey != null && recoverKey.getPubKeyPoint().equals(ecKey.getPubKeyPoint())) {
recId = i;
break;
}
}
if (recId == -1) {
throw new RuntimeException(
"Could not construct a recoverable key. This should never happen.");
}
int headerByte = recId + 27;
// 1 header + 32 bytes for R + 32 bytes for S
byte v = (byte) headerByte;
byte[] r = NumericUtil.bigIntegerToBytesWithZeroPadded(sig.r, 32);
byte[] s = NumericUtil.bigIntegerToBytesWithZeroPadded(sig.s, 32);
return new SignatureData(v, r, s);
}
}
| 5,536 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
TxSignResult.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/transaction/TxSignResult.java | package org.consenlabs.tokencore.wallet.transaction;
/**
* Created by xyz on 2018/1/22.
*/
public class TxSignResult {
private String signedTx;
private String txHash;
private String wtxID;
public String getWtxID() {
return wtxID;
}
public void setWtxID(String wtxID) {
this.wtxID = wtxID;
}
public String getSignedTx() {
return signedTx;
}
public void setSignedTx(String signedTx) {
this.signedTx = signedTx;
}
public String getTxHash() {
return txHash;
}
public void setTxHash(String txHash) {
this.txHash = txHash;
}
public TxSignResult(){
}
public TxSignResult(String signedTx, String txHash) {
this.signedTx = signedTx;
this.txHash = txHash;
}
public TxSignResult(String signedTx, String txHash, String wtxID) {
this.signedTx = signedTx;
this.txHash = txHash;
this.wtxID = wtxID;
}
}
| 938 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
EOSSign.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/transaction/EOSSign.java | package org.consenlabs.tokencore.wallet.transaction;
import org.bitcoinj.core.Base58;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.Sha256Hash;
import org.consenlabs.tokencore.foundation.utils.ByteUtil;
import org.consenlabs.tokencore.foundation.utils.NumericUtil;
import org.consenlabs.tokencore.wallet.model.TokenException;
import org.spongycastle.crypto.digests.RIPEMD160Digest;
import org.spongycastle.crypto.digests.SHA256Digest;
import org.spongycastle.crypto.params.ECPrivateKeyParameters;
import java.math.BigInteger;
import java.util.Arrays;
import static org.bitcoinj.core.ECKey.CURVE;
public class EOSSign {
@Deprecated
public static String sign(byte[] dataSha256, String wif) {
SignatureData signatureData = signAsRecoverable(dataSha256, EOSKey.fromWIF(wif).getECKey());
byte[] sigResult = ByteUtil.concat(NumericUtil.intToBytes(signatureData.getV()), signatureData.getR());
sigResult = ByteUtil.concat(sigResult, signatureData.getS());
return serialEOSSignature(sigResult);
}
public static String sign(byte[] dataSha256, byte[] prvKey) {
ECKey ecKey = EOSKey.fromPrivate(prvKey).getECKey();
SignatureData signatureData = signAsRecoverable(dataSha256, ecKey);
byte[] sigResult = ByteUtil.concat(NumericUtil.intToBytes(signatureData.getV()), signatureData.getR());
sigResult = ByteUtil.concat(sigResult, signatureData.getS());
return serialEOSSignature(sigResult);
}
private static SignatureData signAsRecoverable(byte[] value, ECKey ecKey) {
int recId = -1;
ECKey.ECDSASignature sig = eosSign(value, ecKey.getPrivKey());
for (int i = 0; i < 4; i++) {
ECKey recoverKey = ECKey.recoverFromSignature(i, sig, Sha256Hash.wrap(value), false);
if (recoverKey != null && recoverKey.getPubKeyPoint().equals(ecKey.getPubKeyPoint())) {
recId = i;
break;
}
}
if (recId == -1) {
throw new TokenException("Could not construct a recoverable key. This should never happen.");
}
int headerByte = recId + 27 + 4;
// 1 header + 32 bytes for R + 32 bytes for S
byte v = (byte) headerByte;
byte[] r = NumericUtil.bigIntegerToBytesWithZeroPadded(sig.r, 32);
byte[] s = NumericUtil.bigIntegerToBytesWithZeroPadded(sig.s, 32);
return new SignatureData(v, r, s);
}
private static ECKey.ECDSASignature eosSign(byte[] input, BigInteger privateKeyForSigning) {
EOSECDSASigner signer = new EOSECDSASigner(new MyHMacDSAKCalculator(new SHA256Digest()));
ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privateKeyForSigning, CURVE);
signer.init(true, privKey);
BigInteger[] components = signer.generateSignature(input);
return new ECKey.ECDSASignature(components[0], components[1]).toCanonicalised();
}
private static String serialEOSSignature(byte[] data) {
byte[] toHash = ByteUtil.concat(data, "K1".getBytes());
RIPEMD160Digest digest = new RIPEMD160Digest();
digest.update(toHash, 0, toHash.length);
byte[] out = new byte[20];
digest.doFinal(out, 0);
byte[] checksumBytes = Arrays.copyOfRange(out, 0, 4);
data = ByteUtil.concat(data, checksumBytes);
return "SIG_K1_" + Base58.encode(data);
}
}
| 3,291 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
ChainId.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/model/ChainId.java | package org.consenlabs.tokencore.wallet.model;
public class ChainId {
public static final int BITCOIN_MAINNET = 0;
public static final int BITCOIN_TESTNET = 1;
// ref: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md
public static final int ETHEREUM_MAINNET = 1;
public static final int ETHEREUM_ROPSTEN = 3;
public static final int ETHEREUM_KOVAN = 42;
public static final int ETHEREUM_CLASSIC_MAINNET = 61;
public static final int ETHEREUM_CLASSIC_TESTNET = 62;
public static final int ANY = 999;
public static final String EOS_MAINNET = "aca376f206b8fc25a6ed44dbdc66547c36c6c33e3a119ffbeaef943642f0e906";
}
| 663 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
BIP44Util.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/model/BIP44Util.java | package org.consenlabs.tokencore.wallet.model;
import com.google.common.collect.ImmutableList;
import org.bitcoinj.crypto.ChildNumber;
import java.util.ArrayList;
import java.util.List;
public class BIP44Util {
public final static String BITCOIN_MAINNET_PATH = "m/44'/0'/0'";
public final static String BITCOIN_TESTNET_PATH = "m/44'/1'/0'";
public final static String BITCOIN_SEGWIT_MAIN_PATH = "m/49'/0'/0'";
public final static String BITCOIN_SEGWIT_TESTNET_PATH = "m/49'/1'/0'";
public final static String LITECOIN_MAINNET_PATH = "m/44'/2'/0'";
public final static String DOGECOIN_MAINNET_PATH = "m/44'/3'/0'";
public final static String DASH_MAINNET_PATH = "m/44'/5'/0'";
public final static String BITCOINSV_MAINNET_PATH="m/44'/236'/0'";
public final static String BITCOINCASH_MAINNET_PATH="m/44'/145'/0'";
public final static String ETHEREUM_PATH = "m/44'/60'/0'/0/0";
public final static String EOS_PATH = "m/44'/194'";
public final static String EOS_SLIP48 = "m/48'/4'/0'/0'/0',m/48'/4'/1'/0'/0'";
public final static String EOS_LEDGER = "m/44'/194'/0'/0/0";
public final static String TRON_PATH ="m/44'/195'/0'/0/0";
public final static String FILECOIN_PATH ="m/44'/461'/0'/0/0";
public static ImmutableList<ChildNumber> generatePath(String path) {
List<ChildNumber> list = new ArrayList<>();
for (String p : path.split("/")) {
if ("m".equalsIgnoreCase(p) || "".equals(p.trim())) {
continue;
} else if (p.charAt(p.length() - 1) == '\'') {
list.add(new ChildNumber(Integer.parseInt(p.substring(0, p.length() - 1)), true));
} else {
list.add(new ChildNumber(Integer.parseInt(p), false));
}
}
ImmutableList.Builder<ChildNumber> builder = ImmutableList.builder();
return builder.addAll(list).build();
}
public static String getBTCMnemonicPath(String segWit, boolean isMainnet) {
if (Metadata.P2WPKH.equalsIgnoreCase(segWit)) {
return isMainnet ? BITCOIN_SEGWIT_MAIN_PATH : BITCOIN_SEGWIT_TESTNET_PATH;
} else {
return isMainnet ? BITCOIN_MAINNET_PATH : BITCOIN_TESTNET_PATH;
}
}
}
| 2,175 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
Messages.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/model/Messages.java | package org.consenlabs.tokencore.wallet.model;
public class Messages {
public static final String UNKNOWN = "unknown";
public static final String WALLET_INVALID_PASSWORD = "password_incorrect";
public static final String PASSWORD_BLANK = "password_blank";
public static final String PASSWORD_WEAK = "password_weak";
public static final String MNEMONIC_BAD_WORD = "mnemonic_word_invalid";
public static final String MNEMONIC_INVALID_LENGTH = "mnemonic_length_invalid";
public static final String MNEMONIC_CHECKSUM = "mnemonic_checksum_invalid";
public static final String INVALID_MNEMONIC_PATH = "invalid_mnemonic_path";
public static final String APPLICATION_NOT_READY = "application_not_ready";
public static final String WALLET_NOT_FOUND = "wallet_not_found";
public static final String WALLET_INVALID_KEYSTORE = "keystore_invalid";
public static final String WALLET_STORE_FAIL = "store_wallet_failed";
public static final String WALLET_INVALID = "keystore_invalid";
public static final String KDF_UNSUPPORTED = "kdf_unsupported";
public static final String WALLET_INVALID_TYPE = "unsupported_chain";
public static final String WALLET_INVALID_ADDRESS = "address_invalid";
public static final String INVALID_TRANSACTION_DATA = "transaction_data_invalid";
public static final String WALLET_EXISTS = "address_already_exist";
public static final String INVALID_WALLET_VERSION = "keystore_version_invalid";
public static final String WALLET_HD_NOT_SUPPORT_PRIVATE = "hd_not_support_private";
public static final String WALLET_SHA256 = "sha256";
public static final String IPFS_CHECK_SIGNATURE = "check_signature";
public static final String NOT_UTF8 = "not_utf8";
public static final String MAC_UNMATCH = "mac_unmatch";
public static final String PRIVATE_KEY_ADDRESS_NOT_MATCH = "private_key_address_not_match";
public static final String CAN_NOT_TO_JSON = "can_not_to_json" ;
public static final String CAN_NOT_FROM_JSON = "can_not_from_json" ;
public static final String SCRYPT_PARAMS_INVALID = "scrypt_params_invalid";
public static final String PRF_UNSUPPORTED = "prf_unsupported";
public static final String KDF_PARAMS_INVALID = "kdf_params_invalid";
public static final String CIPHER_FAIL = "cipher_unsupported";
public static final String INVALID_BIG_NUMBER = "big_number_invalid";
public static final String INVALID_NEGATIVE = "negative_invalid";
public static final String INVALID_HEX = "hex_invalid";
public static final String INSUFFICIENT_FUNDS = "insufficient_funds";
public static final String CAN_NOT_FOUND_PRIVATE_KEY = "can_not_found_private_key";
public static final String WIF_WRONG_NETWORK = "wif_wrong_network";
public static final String WIF_INVALID = "wif_invalid";
public static final String PRIVATE_KEY_INVALID = "privatekey_invalid";
public static final String CAN_NOT_EXPORT_MNEMONIC = "not_support_export_keystore";
public static final String INVALID_IDENTITY = "invalid_identity";
public static final String UNSUPPORT_SEND_TARGET = "not_support_send_target";
public static final String ILLEGAL_OPERATION = "illegal_operation";
public static final String UNSUPPORT_ENCRYPTION_DATA_VERSION = "unsupport_encryption_data_version";
public static final String INVALID_ENCRYPTION_DATA_SIGNATURE = "invalid_encryption_data_signature";
public static final String ENCRYPT_XPUB_ERROR = "encrypt_xpub_error";
public static final String SEGWIT_NEEDS_COMPRESS_PUBLIC_KEY = "segwit_needs_compress_public_key";
public static final String EOS_PRIVATE_PUBLIC_NOT_MATCH = "eos_private_public_not_match";
public static final String EOS_PUBLIC_KEY_NOT_FOUND = "eos_public_key_not_found";
public static final String EOS_ACCOUNT_NAME_INVALID = "eos_account_name_invalid";
public static final String AMOUNT_LESS_THAN_MINIMUM = "amount_less_than_minimum";
public static final String KEYSTORE_CONTAINS_INVALID_PRIVATE_KEY = "keystore_contains_invalid_private_key";
public static final String REQUIRED_EOS_WALLET = "required_eos_wallet";
}
| 4,155 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
EOSContract.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/model/EOSContract.java | package org.consenlabs.tokencore.wallet.model;
/**
*
* Created by pie on 2019-03-05 23: 43.
*/
public class EOSContract {
public static final String TRANSFER="eosio.token";
}
| 185 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
TokenException.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/model/TokenException.java | package org.consenlabs.tokencore.wallet.model;
public class TokenException extends RuntimeException {
private static final long serialVersionUID = 4300404932829403534L;
public TokenException(String message) {
super(message);
}
public TokenException(String message, Exception e) {
super(message, e);
}
}
| 339 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
MultiTo.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/model/MultiTo.java | package org.consenlabs.tokencore.wallet.model;
/**
*
* Created by pie on 2020/8/9 18: 37.
*/
public class MultiTo{
public MultiTo(String to, long amount) {
this.to = to;
this.amount = amount;
}
private String to;
private long amount;
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public long getAmount() {
return amount;
}
public void setAmount(long amount) {
this.amount = amount;
}
}
| 531 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
KeyPair.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/model/KeyPair.java | package org.consenlabs.tokencore.wallet.model;
import java.util.Objects;
public class KeyPair {
String privateKey;
String publicKey;
public KeyPair() {
}
public KeyPair(String privateKey, String publicKey) {
this.privateKey = privateKey;
this.publicKey = publicKey;
}
public String getPrivateKey() {
return privateKey;
}
public void setPrivateKey(String privateKey) {
this.privateKey = privateKey;
}
public String getPublicKey() {
return publicKey;
}
public void setPublicKey(String publicKey) {
this.publicKey = publicKey;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
KeyPair keyPair = (KeyPair) o;
return Objects.equals(privateKey, keyPair.privateKey) &&
Objects.equals(publicKey, keyPair.publicKey);
}
@Override
public int hashCode() {
return Objects.hash(privateKey, publicKey);
}
}
| 1,027 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
MnemonicAndPath.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/model/MnemonicAndPath.java | package org.consenlabs.tokencore.wallet.model;
public class MnemonicAndPath {
public String getMnemonic() {
return mnemonic;
}
public String getPath() {
return path;
}
private final String mnemonic;
private final String path;
public MnemonicAndPath(String mnemonic, String path) {
this.path = path;
this.mnemonic = mnemonic;
}
}
| 384 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
Metadata.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/model/Metadata.java | package org.consenlabs.tokencore.wallet.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.ArrayList;
import java.util.List;
public class Metadata implements Cloneable {
public static final String FROM_MNEMONIC = "MNEMONIC";
public static final String FROM_KEYSTORE = "KEYSTORE";
public static final String FROM_PRIVATE = "PRIVATE";
public static final String FROM_WIF = "WIF";
public static final String FROM_NEW_IDENTITY = "NEW_IDENTITY";
public static final String FROM_RECOVERED_IDENTITY = "RECOVERED_IDENTITY";
public static final String P2WPKH = "P2WPKH";
public static final String NONE = "NONE";
public static final String NORMAL = "NORMAL";
public static final String HD = "HD";
public static final String RANDOM = "RANDOM";
public static final String HD_SHA256 = "HD_SHA256";
public static final String V3 = "V3";
private String name;
private String passwordHint;
private String chainType;
private long timestamp;
private String network;
private List<String> backup = new ArrayList<>();
private String source;
private String mode = NORMAL;
private String walletType;
private String segWit;
// for jackson serial
public Metadata() {
}
@Override
public Metadata clone() {
Metadata metadata = null;
try {
metadata = (Metadata) super.clone();
} catch (CloneNotSupportedException ex) {
throw new TokenException("Clone metadata filed");
}
metadata.backup = new ArrayList<>(backup);
return metadata;
}
public String getSegWit() {
return segWit;
}
public void setSegWit(String segWit) {
this.segWit = segWit;
}
public Metadata(String type, String network, String name, String passwordHint) {
this.chainType = type;
this.name = name;
this.passwordHint = passwordHint;
this.timestamp = System.currentTimeMillis() / 1000;
this.network = network;
}
public Metadata(String type, String network, String name, String passwordHint, String segWit) {
this.chainType = type;
this.name = name;
this.passwordHint = passwordHint;
this.timestamp = System.currentTimeMillis() / 1000;
this.network = network;
this.segWit = segWit;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPasswordHint() {
return passwordHint;
}
public void setPasswordHint(String passwordHint) {
this.passwordHint = passwordHint;
}
public String getChainType() {
return chainType;
}
public void setChainType(String chainType) {
this.chainType = chainType;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public List<String> getBackup() {
return backup;
}
public void setBackup(List<String> backup) {
this.backup = backup;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getMode() {
return mode;
}
public void setMode(String mode) {
this.mode = mode;
}
public String getWalletType() {
return walletType;
}
public void setWalletType(String walletType) {
this.walletType = walletType;
}
@JsonIgnore
public Boolean isMainNet() {
return Network.MAINNET.equalsIgnoreCase(network);
}
public String getNetwork() {
return network;
}
public void setNetwork(String network) {
this.network = network;
}
}
| 3,710 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
ChainType.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/model/ChainType.java | package org.consenlabs.tokencore.wallet.model;
public class ChainType {
public final static String ETHEREUM = "ETHEREUM";
public final static String BITCOIN = "BITCOIN";
public final static String EOS = "EOS";
public final static String LITECOIN = "LITECOIN";
public final static String DASH = "DASH";
public final static String BITCOINCASH = "BITCOINCASH";
public final static String BITCOINSV = "BITCOINSV";
public final static String DOGECOIN = "DOGECOIN";
public final static String TRON = "TRON";
public final static String FILECOIN = "FILECOIN";
public static void validate(String type) {
if (!ETHEREUM.equals(type) &&
!BITCOIN.equals(type) &&
!EOS.equals(type) &&
!LITECOIN.equals(type) &&
!DASH.equals(type) &&
!BITCOINSV.equals(type) &&
!BITCOINCASH.equals(type) &&
!DOGECOIN.equals(type) &&
!TRON.equals(type)&&
!FILECOIN.equals(type)) {
throw new TokenException(Messages.WALLET_INVALID_TYPE);
}
}
}
| 1,163 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
Network.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/wallet/model/Network.java | package org.consenlabs.tokencore.wallet.model;
/**
* Created by xyz on 2018/3/7.
*/
public class Network {
public static final String MAINNET = "MAINNET";
public static final String TESTNET = "TESTNET";
public static final String KOVAN = "KOVAN";
public static final String ROPSTEN = "ROPSTEN";
private String network;
public Network(String network) {
this.network = network;
}
public boolean isMainnet() {
return MAINNET.equalsIgnoreCase(this.network);
}
}
| 513 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
Crypto.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/foundation/crypto/Crypto.java | package org.consenlabs.tokencore.foundation.crypto;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.google.common.base.Strings;
import org.consenlabs.tokencore.foundation.utils.CachedDerivedKey;
import org.consenlabs.tokencore.foundation.utils.NumericUtil;
import org.consenlabs.tokencore.wallet.model.Messages;
import org.consenlabs.tokencore.wallet.model.TokenException;
import java.util.Arrays;
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.EXISTING_PROPERTY,
property = "kdf")
@JsonSubTypes({
@JsonSubTypes.Type(value = SCryptCrypto.class, name = "scrypt"),
@JsonSubTypes.Type(value = PBKDF2Crypto.class, name = "pbkdf2")
})
public class Crypto<T extends KDFParams> {
static final String CTR = "aes-128-ctr";
static final String CBC = "aes-128-cbc";
static final int IV_LENGTH = 16;
static final int SALT_LENGTH = 32;
private String ciphertext;
private String mac;
String cipher;
private CipherParams cipherparams;
/**
* !!! This function is used for testcase, and do not call this in other places;
*
* @return
*/
CachedDerivedKey getCachedDerivedKey() {
return cachedDerivedKey;
}
@JsonIgnore
private CachedDerivedKey cachedDerivedKey;
private void setCachedDerivedKey(CachedDerivedKey cachedDerivedKey) {
this.cachedDerivedKey = cachedDerivedKey;
}
String kdf;
T kdfparams;
public static Crypto createPBKDF2Crypto(String password, byte[] origin) {
return createCrypto(password, origin, PBKDF2Crypto.PBKDF2, false);
}
public static Crypto createPBKDF2CryptoWithKDFCached(String password, byte[] origin) {
return createCrypto(password, origin, PBKDF2Crypto.PBKDF2, true);
}
public static Crypto createSCryptCrypto(String password, byte[] origin) {
return createCrypto(password, origin, SCryptCrypto.SCRYPT, false);
}
private static Crypto createCrypto(String password, byte[] origin, String kdfType, boolean isCached) {
Crypto crypto = PBKDF2Crypto.PBKDF2.equals(kdfType) ? PBKDF2Crypto.createPBKDF2Crypto() : SCryptCrypto.createSCryptCrypto();
crypto.setCipher(CTR);
byte[] iv = NumericUtil.generateRandomBytes(IV_LENGTH);
CipherParams cipherparams = new CipherParams();
cipherparams.setIv(NumericUtil.bytesToHex(iv));
crypto.setCipherparams(cipherparams);
byte[] derivedKey = crypto.getValidDerivedKey(password);
if (isCached) {
crypto.setCachedDerivedKey(new CachedDerivedKey(password, derivedKey));
}
byte[] encrypted = crypto.encrypt(derivedKey, iv, origin);
crypto.ciphertext = NumericUtil.bytesToHex(encrypted);
byte[] mac = Hash.generateMac(derivedKey, encrypted);
crypto.mac = NumericUtil.bytesToHex(mac);
return crypto;
}
Crypto() {
}
public boolean verifyPassword(String password) {
try {
getCachedDerivedKey(password);
return true;
} catch (Exception ignored) {
return false;
}
}
public void cacheDerivedKey(String password) {
byte[] derivedKey = getValidDerivedKey(password);
this.cachedDerivedKey = new CachedDerivedKey(password, derivedKey);
}
private byte[] getCachedDerivedKey(String password) {
if (cachedDerivedKey != null) {
byte[] derivedKey = cachedDerivedKey.getDerivedKey(password);
if (derivedKey != null) {
return derivedKey;
}
}
return getValidDerivedKey(password);
}
public void clearCachedDerivedKey() {
this.cachedDerivedKey = null;
}
private byte[] getValidDerivedKey(String password) {
byte[] derivedKey = generateDerivedKey(password.getBytes());
if (this.mac == null) return derivedKey;
byte[] mac = NumericUtil.hexToBytes(this.mac);
byte[] cipherText = NumericUtil.hexToBytes(getCiphertext());
byte[] derivedMac = Hash.generateMac(derivedKey, cipherText);
if (Arrays.equals(derivedMac, mac)) {
return derivedKey;
} else {
throw new TokenException(Messages.WALLET_INVALID_PASSWORD);
}
}
public void validate() {
if ((!CTR.equals(cipher) && !CBC.equals(cipher)) || cipherparams == null
|| Strings.isNullOrEmpty(mac) || Strings.isNullOrEmpty(ciphertext)
|| kdfparams == null) {
throw new TokenException(Messages.WALLET_INVALID);
}
cipherparams.validate();
kdfparams.validate();
}
byte[] generateDerivedKey(byte[] password) {
throw new UnsupportedOperationException("You invoke the not implement method");
}
private byte[] encrypt(byte[] derivedKey, byte[] iv, byte[] text) {
byte[] encryptKey = Arrays.copyOfRange(derivedKey, 0, 16);
if (CTR.equals(cipher)) {
return AES.encryptByCTRNoPadding(text, encryptKey, iv);
} else {
return AES.encryptByCBCNoPadding(text, encryptKey, iv);
}
}
public byte[] decrypt(String password) {
byte[] derivedKey = getCachedDerivedKey(password);
byte[] iv = NumericUtil.hexToBytes(this.getCipherparams().getIv());
byte[] encrypted = NumericUtil.hexToBytes(this.getCiphertext());
return decrypt(derivedKey, iv, encrypted);
}
private byte[] decrypt(byte[] derivedKey, byte[] iv, byte[] text) {
byte[] encryptKey = Arrays.copyOfRange(derivedKey, 0, 16);
if (CTR.equals(cipher)) {
return AES.decryptByCTRNoPadding(text, encryptKey, iv);
} else {
return AES.decryptByCBCNoPadding(text, encryptKey, iv);
}
}
public EncPair deriveEncPair(String password, byte[] origin) {
byte[] derivedKey = getCachedDerivedKey(password);
EncPair encPair = new EncPair();
byte[] iv = NumericUtil.generateRandomBytes(16);
byte[] encrypted = this.encrypt(derivedKey, iv, origin);
encPair.setEncStr(NumericUtil.bytesToHex(encrypted));
encPair.setNonce(NumericUtil.bytesToHex(iv));
return encPair;
}
public byte[] decryptEncPair(String password, EncPair encPair) {
byte[] derivedKey = getCachedDerivedKey(password);
byte[] iv = NumericUtil.hexToBytes(encPair.getNonce());
return decrypt(derivedKey, iv, NumericUtil.hexToBytes(encPair.getEncStr()));
}
@JsonProperty(required = true)
public String getCiphertext() {
return ciphertext;
}
@JsonProperty(required = true)
public CipherParams getCipherparams() {
return cipherparams;
}
@JsonProperty(required = true)
public String getMac() {
return mac;
}
@JsonProperty(required = true)
public String getCipher() {
return cipher;
}
@JsonProperty(required = true)
public String getKdf() {
return kdf;
}
@JsonProperty(required = true)
public T getKdfparams() {
return kdfparams;
}
public void setCiphertext(String ciphertext) {
this.ciphertext = ciphertext;
}
public void setMac(String mac) {
this.mac = mac;
}
public void setCipher(String cipher) {
this.cipher = cipher;
}
public void setCipherparams(CipherParams cipherparams) {
this.cipherparams = cipherparams;
}
public void setKdf(String kdf) {
this.kdf = kdf;
}
public void setKdfparams(T kdfparams) {
this.kdfparams = kdfparams;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Crypto)) {
return false;
}
Crypto that = (Crypto) o;
if (cipher != null
? !cipher.equals(that.cipher)
: that.cipher != null) {
return false;
}
if (getCiphertext() != null
? !getCiphertext().equals(that.getCiphertext())
: that.getCiphertext() != null) {
return false;
}
if (getCipherparams() != null
? !getCipherparams().equals(that.getCipherparams())
: that.getCipherparams() != null) {
return false;
}
if (kdf != null
? !kdf.equals(that.kdf)
: that.kdf != null) {
return false;
}
if (this.kdfparams != null
? !this.kdfparams.equals(that.kdfparams)
: that.kdfparams != null) {
return false;
}
return mac != null
? mac.equals(that.mac) : that.mac == null;
}
@Override
public int hashCode() {
int result = cipher != null ? cipher.hashCode() : 0;
result = 31 * result + (getCiphertext() != null ? getCiphertext().hashCode() : 0);
result = 31 * result + (getCipherparams() != null ? getCipherparams().hashCode() : 0);
result = 31 * result + (kdf != null ? kdf.hashCode() : 0);
result = 31 * result + (this.kdfparams != null ? this.kdfparams.hashCode() : 0);
result = 31 * result + (mac != null ? mac.hashCode() : 0);
return result;
}
}
| 9,002 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
CipherParams.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/foundation/crypto/CipherParams.java | package org.consenlabs.tokencore.foundation.crypto;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.base.Strings;
import org.consenlabs.tokencore.wallet.model.Messages;
import org.consenlabs.tokencore.wallet.model.TokenException;
/**
* Created by xyz on 2018/2/3.
*/
public class CipherParams {
private String iv;
CipherParams() {
}
public String getIv() {
return iv;
}
public void setIv(String iv) {
this.iv = iv;
}
@JsonIgnore
public void validate() {
if (Strings.isNullOrEmpty(iv)) {
throw new TokenException(Messages.CIPHER_FAIL);
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof CipherParams)) {
return false;
}
CipherParams that = (CipherParams) o;
return getIv() != null
? getIv().equals(that.getIv()) : that.getIv() == null;
}
@Override
public int hashCode() {
return getIv() != null ? getIv().hashCode() : 0;
}
}
| 1,068 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
Hash.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/foundation/crypto/Hash.java | package org.consenlabs.tokencore.foundation.crypto;
import org.bitcoinj.core.Sha256Hash;
import org.consenlabs.tokencore.foundation.utils.ByteUtil;
import org.consenlabs.tokencore.foundation.utils.NumericUtil;
import org.consenlabs.tokencore.wallet.model.Messages;
import org.consenlabs.tokencore.wallet.model.TokenException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Hash {
public static String keccak256(String hex) {
byte[] bytes = NumericUtil.hexToBytes(hex);
byte[] result = keccak256(bytes);
return NumericUtil.bytesToHex(result);
}
public static byte[] keccak256(byte[] input) {
return keccak256(input, 0, input.length);
}
public static byte[] generateMac(byte[] derivedKey, byte[] cipherText) {
byte[] result = new byte[16 + cipherText.length];
System.arraycopy(derivedKey, 16, result, 0, 16);
System.arraycopy(cipherText, 0, result, 16, cipherText.length);
return Hash.keccak256(result);
}
public static String sha256(String hexInput) {
byte[] bytes = NumericUtil.hexToBytes(hexInput);
byte[] result = sha256(bytes);
return NumericUtil.bytesToHex(result);
}
public static byte[] sha256(byte[] input) {
return sha256(input, 0, input.length);
}
private static byte[] keccak256(byte[] input, int offset, int length) {
Keccak keccak = new Keccak(256);
keccak.update(input, offset, length);
return keccak.digest().array();
}
private static byte[] sha256(byte[] input, int offset, int length) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(input, offset, length);
return md.digest();
} catch (Exception ex) {
throw new TokenException(Messages.WALLET_SHA256);
}
}
public static byte[] hmacSHA256(byte[] key, byte[] data) {
try {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(key, "HmacSHA256");
sha256_HMAC.init(secret_key);
return sha256_HMAC.doFinal(data);
} catch (NoSuchAlgorithmException | InvalidKeyException ex) {
throw new TokenException(Messages.WALLET_SHA256);
}
}
public static byte[] merkleHash(byte[] oriData) {
if (oriData == null || oriData.length == 0) {
throw new IllegalArgumentException("data should not be null");
}
int chunkSize = 1024;
List<byte[]> hashes = new ArrayList<>();
for (int pos = 0; pos < oriData.length; pos += chunkSize) {
int end = Math.min(pos + chunkSize, oriData.length);
hashes.add(Sha256Hash.hashTwice(Arrays.copyOfRange(oriData, pos, end)));
}
int j = 0;
for (int size = hashes.size(); size > 1; size = (size + 1) / 2) {
for (int i = 0; i < size; i += 2) {
int i2 = Math.min(i + 1, size - 1);
hashes.add(Sha256Hash.hashTwice(ByteUtil.concat(hashes.get(j + i), hashes.get(j + i2))));
}
j += size;
}
return hashes.get(hashes.size() - 1);
}
}
| 3,286 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
PBKDF2Params.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/foundation/crypto/PBKDF2Params.java | package org.consenlabs.tokencore.foundation.crypto;
import com.google.common.base.Strings;
import org.consenlabs.tokencore.wallet.model.Messages;
import org.consenlabs.tokencore.wallet.model.TokenException;
/**
* Created by xyz on 2018/2/2.
*/
public class PBKDF2Params implements KDFParams {
static final String PRF = "hmac-sha256";
static final int C_LIGHT = 10240;
private int dklen = 0;
private int c = 0;
private String prf = "";
private String salt;
public PBKDF2Params() {
}
public static PBKDF2Params createPBKDF2Params() {
PBKDF2Params params = new PBKDF2Params();
params.dklen = DK_LEN;
params.c = C_LIGHT;
params.prf = PRF;
return params;
}
public int getDklen() {
return dklen;
}
public void setDklen(int dklen) {
this.dklen = dklen;
}
public int getC() {
return c;
}
public void setC(int c) {
this.c = c;
}
public String getPrf() {
return prf;
}
public void setPrf(String prf) {
this.prf = prf;
}
public String getSalt() {
return salt;
}
@Override
public void validate() {
if (dklen == 0 || c == 0 || Strings.isNullOrEmpty(salt) || Strings.isNullOrEmpty(prf)) {
throw new TokenException(Messages.KDF_PARAMS_INVALID);
}
}
public void setSalt(String salt) {
this.salt = salt;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof PBKDF2Params)) {
return false;
}
PBKDF2Params that = (PBKDF2Params) o;
if (dklen != that.dklen) {
return false;
}
if (c != that.c) {
return false;
}
if (getPrf() != null
? !getPrf().equals(that.getPrf())
: that.getPrf() != null) {
return false;
}
return getSalt() != null
? getSalt().equals(that.getSalt()) : that.getSalt() == null;
}
@Override
public int hashCode() {
int result = dklen;
result = 31 * result + c;
result = 31 * result + (getPrf() != null ? getPrf().hashCode() : 0);
result = 31 * result + (getSalt() != null ? getSalt().hashCode() : 0);
return result;
}
}
| 2,239 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
Keccak.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/foundation/crypto/Keccak.java | package org.consenlabs.tokencore.foundation.crypto;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class Keccak {
private static final int MAX_STATE_SIZE = 1600;
private static final int MAX_STATE_SIZE_WORDS = MAX_STATE_SIZE / 64;
private int rateSizeBits, digestSizeBits;
private long[] state = new long[MAX_STATE_SIZE_WORDS];
private int rateBits;
private boolean padded;
Keccak(int digestSizeBits) {
reset(digestSizeBits);
}
public Keccak(Keccak other) {
System.arraycopy(other.state, 0, state, 0, other.state.length);
rateBits = other.rateBits;
rateSizeBits = other.rateSizeBits;
digestSizeBits = other.digestSizeBits;
padded = other.padded;
}
@Override
public String toString() {
return "Keccak-" + digestSizeBits;
}
public int rateSize() {
return rateSizeBits >>> 3;
}
private int digestSize() {
return digestSizeBits >>> 3;
}
public void reset() {
reset(rateSizeBits, digestSizeBits);
}
private int rateSizeBitsFor(int digestSizeBits) {
//@formatter:off
switch (digestSizeBits) {
case 288:
return 1024;
case 128:
return 1344;
case 224:
return 1152;
case 256:
return 1088;
case 384:
return 832;
case 512:
return 576;
default:
throw new IllegalArgumentException("Invalid digestSizeBits: " + digestSizeBits + " ⊄ { 128, 224, 256, 288, 384, 512 }");
}
//@formatter:on
}
private void reset(int digestSizeBits) {
reset(rateSizeBitsFor(digestSizeBits), digestSizeBits);
}
private void reset(int rateSizebits, int digestSizeBits) {
if (rateSizebits + digestSizeBits * 2 != MAX_STATE_SIZE)
throw new IllegalArgumentException("Invalid rateSizebits + digestSizeBits * 2: " + rateSizebits + " + " + digestSizeBits + " * 2 != " + MAX_STATE_SIZE);
if (rateSizebits <= 0 || (rateSizebits & 0x3f) > 0)
throw new IllegalArgumentException("Invalid rateSizebits: " + rateSizebits);
for (int i = 0; i < MAX_STATE_SIZE_WORDS; ++i)
state[i] = 0;
rateBits = 0;
rateSizeBits = rateSizebits;
this.digestSizeBits = digestSizeBits;
padded = false;
}
public void update(byte in) {
updateBits(in & 0xff, 8);
}
public void update(byte[] in) {
update(ByteBuffer.wrap(in));
}
void update(byte[] in, int offset, int length) {
update(ByteBuffer.wrap(in, offset, length));
}
private void update(ByteBuffer in) {
int inBytes = in.remaining();
if (inBytes <= 0)
return;
if (padded)
throw new IllegalStateException("Cannot update while padded");
int rateBits = this.rateBits;
if ((rateBits & 0x7) > 0) //this could be implemented but would introduce considerable performance degradation - also, it's never technically possible.
throw new IllegalStateException("Cannot update while in bit-mode");
long[] state = this.state;
int rateBytes = rateBits >>> 3;
int rateBytesWord = rateBytes & 0x7;
if (rateBytesWord > 0) {
//logically must have space at this point
int c = 8 - rateBytesWord;
if (c > inBytes)
c = inBytes;
int i = rateBytes >>> 3;
long w = state[i];
rateBytes += c;
inBytes -= c;
rateBytesWord <<= 3;
c = rateBytesWord + (c << 3);
do {
w ^= (long) (in.get() & 0xff) << rateBytesWord;
rateBytesWord += 8;
} while (rateBytesWord < c);
state[i] = w;
if (inBytes > 0) {
this.rateBits = rateBytes << 3;
return;
}
}
int rateWords = rateBytes >>> 3;
int rateSizeWords = rateSizeBits >>> 6;
int inWords = inBytes >>> 3;
if (inWords > 0) {
ByteOrder order = in.order();
try {
in.order(ByteOrder.LITTLE_ENDIAN);
do {
if (rateWords >= rateSizeWords) {
Keccak.keccak(state);
rateWords = 0;
}
int c = rateSizeWords - rateWords;
if (c > inWords)
c = inWords;
inWords -= c;
c += rateWords;
do {
state[rateWords] ^= in.getLong();
rateWords++;
} while (rateWords < c);
} while (inWords > 0);
} finally {
in.order(order);
}
inBytes &= 0x7;
if (inBytes <= 0) {
this.rateBits = rateWords << 6;
return;
}
}
if (rateWords >= rateSizeWords) {
Keccak.keccak(state);
rateWords = 0;
}
long w = state[rateWords];
inBytes <<= 3;
int i = 0;
do {
w ^= (long) (in.get() & 0xff) << i;
i += 8;
} while (i < inBytes);
state[rateWords] = w;
this.rateBits = (rateWords << 6) | inBytes;
}
private void updateBits(long in, int inBits) {
if (inBits < 0 || inBits > 64)
throw new IllegalArgumentException("Invalid valueBits: " + 0 + " < " + inBits + " > " + 64);
if (inBits <= 0)
return;
if (padded)
throw new IllegalStateException("Cannot update while padded");
long[] state = this.state;
int rateBits = this.rateBits;
int rateBitsWord = rateBits & 0x3f;
if (rateBitsWord > 0) {
//logically must have space at this point
int c = 64 - rateBitsWord;
if (c > inBits)
c = inBits;
state[rateBits >>> 6] ^= (in & (-1L >>> c)) << rateBitsWord;
rateBits += c;
inBits -= c;
if (inBits <= 0) {
this.rateBits = rateBits;
return;
}
in >>>= c;
}
if (rateBits >= rateSizeBits) {
Keccak.keccak(state);
rateBits = 0;
}
state[rateBits >>> 6] ^= in & (-1L >>> inBits);
this.rateBits = rateBits + inBits;
}
ByteBuffer digest() {
return digest(digestSize());
}
private ByteBuffer digest(int outSize) {
return digest(outSize, false);
}
private ByteBuffer digest(int outSize, boolean direct) {
ByteBuffer buffer = direct ? ByteBuffer.allocateDirect(outSize) : ByteBuffer.allocate(outSize);
digest(buffer);
buffer.flip();
return buffer;
}
public byte[] digestArray() {
return digestArray(digestSize());
}
private byte[] digestArray(int outSize) {
byte[] array = new byte[outSize];
digest(array, 0, outSize);
return array;
}
public void digest(byte[] out) {
digest(ByteBuffer.wrap(out));
}
private void digest(byte[] out, int offset, int length) {
digest(ByteBuffer.wrap(out, offset, length));
}
private void digest(ByteBuffer out) {
int outBytes = out.remaining();
if (outBytes <= 0)
return;
long[] state = this.state;
int rateBits = this.rateBits;
int rateBytes;
if (!padded) {
pad();
padded = true;
rateBits = 0;
rateBytes = 0;
} else {
if ((rateBits & 0x7) > 0)
throw new IllegalStateException("Cannot digest while in bit-mode"); //this could be implemented but would introduce considerable performance degradation - also, it's never technically possible.
rateBytes = rateBits >>> 3;
int rateBytesWord = rateBytes & 0x7;
if (rateBytesWord > 0) {
int c = 8 - rateBytesWord;
if (c > outBytes)
c = outBytes;
long w = state[rateBytes >>> 3];
outBytes -= c;
rateBytes += c;
rateBytesWord <<= 3;
c = (c << 3) + rateBytesWord;
do {
out.put((byte) (w >>> rateBytesWord));
rateBytesWord += 8;
} while (rateBytesWord < c);
if (outBytes <= 0) {
this.rateBits = rateBytes << 3;
return;
}
}
}
int rateSizeWords = rateSizeBits >>> 6;
int rateWords = rateBytes >>> 3;
int outWords = outBytes >>> 3;
if (outWords > 0) {
ByteOrder order = out.order();
try {
out.order(ByteOrder.LITTLE_ENDIAN);
do {
if (rateWords >= rateSizeWords) {
squeeze();
rateWords = 0;
}
int c = rateSizeWords - rateWords;
if (c > outWords)
c = outWords;
outWords -= c;
c += rateWords;
do {
out.putLong(state[rateWords]);
rateWords++;
} while (rateWords < c);
} while (outWords > 0);
} finally {
out.order(order);
}
outBytes &= 0x7;
if (outBytes <= 0) {
this.rateBits = rateWords << 6;
return;
}
}
if (rateWords >= rateSizeWords) {
squeeze();
rateWords = 0;
}
long w = state[rateWords];
outBytes <<= 3;
int i = 0;
do {
out.put((byte) (w >>> i));
i += 8;
} while (i < outBytes);
this.rateBits = (rateWords << 6) | outBytes;
}
private void squeeze() {
Keccak.keccak(state);
}
private void pad() {
updateBits(0x1, 1);
if (rateBits >= rateSizeBits) {
Keccak.keccak(state);
rateBits = 0;
}
rateBits = rateSizeBits - 1;
updateBits(0x1, 1);
Keccak.keccak(state);
}
private static void keccak(long[] a) {
//@formatter:off
int c, i;
long x, a_10_;
long x0, x1, x2, x3, x4;
long t0, t1, t2, t3, t4;
long c0, c1, c2, c3, c4;
i = 0;
do {
//theta (precalculation part)
c0 = a[0] ^ a[5 + 0] ^ a[10 + 0] ^ a[15 + 0] ^ a[20 + 0];
c1 = a[1] ^ a[5 + 1] ^ a[10 + 1] ^ a[15 + 1] ^ a[20 + 1];
c2 = a[2] ^ a[5 + 2] ^ a[10 + 2] ^ a[15 + 2] ^ a[20 + 2];
c3 = a[3] ^ a[5 + 3] ^ a[10 + 3] ^ a[15 + 3] ^ a[20 + 3];
c4 = a[4] ^ a[5 + 4] ^ a[10 + 4] ^ a[15 + 4] ^ a[20 + 4];
t0 = (c0 << 1) ^ (c0 >>> (64 - 1)) ^ c3;
t1 = (c1 << 1) ^ (c1 >>> (64 - 1)) ^ c4;
t2 = (c2 << 1) ^ (c2 >>> (64 - 1)) ^ c0;
t3 = (c3 << 1) ^ (c3 >>> (64 - 1)) ^ c1;
t4 = (c4 << 1) ^ (c4 >>> (64 - 1)) ^ c2;
//theta (xorring part) + rho + pi
a[0] ^= t1;
x = a[1] ^ t2;
a_10_ = (x << 1) | (x >>> (64 - 1));
x = a[6] ^ t2;
a[1] = (x << 44) | (x >>> (64 - 44));
x = a[9] ^ t0;
a[6] = (x << 20) | (x >>> (64 - 20));
x = a[22] ^ t3;
a[9] = (x << 61) | (x >>> (64 - 61));
x = a[14] ^ t0;
a[22] = (x << 39) | (x >>> (64 - 39));
x = a[20] ^ t1;
a[14] = (x << 18) | (x >>> (64 - 18));
x = a[2] ^ t3;
a[20] = (x << 62) | (x >>> (64 - 62));
x = a[12] ^ t3;
a[2] = (x << 43) | (x >>> (64 - 43));
x = a[13] ^ t4;
a[12] = (x << 25) | (x >>> (64 - 25));
x = a[19] ^ t0;
a[13] = (x << 8) | (x >>> (64 - 8));
x = a[23] ^ t4;
a[19] = (x << 56) | (x >>> (64 - 56));
x = a[15] ^ t1;
a[23] = (x << 41) | (x >>> (64 - 41));
x = a[4] ^ t0;
a[15] = (x << 27) | (x >>> (64 - 27));
x = a[24] ^ t0;
a[4] = (x << 14) | (x >>> (64 - 14));
x = a[21] ^ t2;
a[24] = (x << 2) | (x >>> (64 - 2));
x = a[8] ^ t4;
a[21] = (x << 55) | (x >>> (64 - 55));
x = a[16] ^ t2;
a[8] = (x << 45) | (x >>> (64 - 45));
x = a[5] ^ t1;
a[16] = (x << 36) | (x >>> (64 - 36));
x = a[3] ^ t4;
a[5] = (x << 28) | (x >>> (64 - 28));
x = a[18] ^ t4;
a[3] = (x << 21) | (x >>> (64 - 21));
x = a[17] ^ t3;
a[18] = (x << 15) | (x >>> (64 - 15));
x = a[11] ^ t2;
a[17] = (x << 10) | (x >>> (64 - 10));
x = a[7] ^ t3;
a[11] = (x << 6) | (x >>> (64 - 6));
x = a[10] ^ t1;
a[7] = (x << 3) | (x >>> (64 - 3));
a[10] = a_10_;
//chi
c = 0;
do {
x0 = a[c + 0];
x1 = a[c + 1];
x2 = a[c + 2];
x3 = a[c + 3];
x4 = a[c + 4];
a[c + 0] = x0 ^ ((~x1) & x2);
a[c + 1] = x1 ^ ((~x2) & x3);
a[c + 2] = x2 ^ ((~x3) & x4);
a[c + 3] = x3 ^ ((~x4) & x0);
a[c + 4] = x4 ^ ((~x0) & x1);
c += 5;
} while (c < 25);
//iota
a[0] ^= RC[i];
i++;
} while (i < 24);
//@formatter:on
}
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};
}
| 12,956 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
AES.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/foundation/crypto/AES.java | package org.consenlabs.tokencore.foundation.crypto;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AES {
public enum AESType {
CTR, CBC
}
public static byte[] encryptByCTR(byte[] data, byte[] key, byte[] iv) {
return doAES(data, key, iv, Cipher.ENCRYPT_MODE, AESType.CTR, "PKCS5Padding");
}
public static byte[] decryptByCTR(byte[] ciphertext, byte[] key, byte[] iv) {
return doAES(ciphertext, key, iv, Cipher.DECRYPT_MODE, AESType.CTR, "PKCS5Padding");
}
public static byte[] encryptByCBC(byte[] data, byte[] key, byte[] iv) {
return doAES(data, key, iv, Cipher.ENCRYPT_MODE, AESType.CBC, "PKCS5Padding");
}
public static byte[] decryptByCBC(byte[] ciphertext, byte[] key, byte[] iv) {
return doAES(ciphertext, key, iv, Cipher.DECRYPT_MODE, AESType.CBC, "PKCS5Padding");
}
public static byte[] encryptByCTRNoPadding(byte[] data, byte[] key, byte[] iv) {
return doAES(data, key, iv, Cipher.ENCRYPT_MODE, AESType.CTR, "NoPadding");
}
public static byte[] decryptByCTRNoPadding(byte[] ciphertext, byte[] key, byte[] iv) {
return doAES(ciphertext, key, iv, Cipher.DECRYPT_MODE, AESType.CTR, "NoPadding");
}
public static byte[] encryptByCBCNoPadding(byte[] data, byte[] key, byte[] iv) {
return doAES(data, key, iv, Cipher.ENCRYPT_MODE, AESType.CBC, "NoPadding");
}
public static byte[] decryptByCBCNoPadding(byte[] ciphertext, byte[] key, byte[] iv) {
return doAES(ciphertext, key, iv, Cipher.DECRYPT_MODE, AESType.CBC, "NoPadding");
}
private static byte[] doAES(byte[] data, byte[] key, byte[] iv, int cipherMode, AESType type, String paddingType) {
String aesType;
if (type == AESType.CBC) {
aesType = "CBC";
} else {
aesType = "CTR";
}
try {
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
String algorithmDesc = String.format("AES/%s/%s", aesType, paddingType);
Cipher cipher = Cipher.getInstance(algorithmDesc);
cipher.init(cipherMode, secretKeySpec, ivParameterSpec);
return cipher.doFinal(data);
} catch (Exception ignored) {
}
return new byte[0];
}
}
| 2,341 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
EncPair.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/foundation/crypto/EncPair.java | package org.consenlabs.tokencore.foundation.crypto;
public class EncPair {
private String encStr;
private String nonce;
public String getNonce() {
return nonce;
}
public void setNonce(String nonce) {
this.nonce = nonce;
}
public String getEncStr() {
return encStr;
}
public void setEncStr(String encStr) {
this.encStr = encStr;
}
}
| 397 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
Multihash.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/foundation/crypto/Multihash.java | package org.consenlabs.tokencore.foundation.crypto;
import org.bitcoinj.core.Base58;
import java.io.ByteArrayOutputStream;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;
public class Multihash {
public enum Type {
md5(0xd5, 16),
sha1(0x11, 20),
sha2_256(0x12, 32),
sha2_512(0x13, 64),
sha3_512(0x14, 64),
blake2b(0x40, 64),
blake2s(0x41, 32);
public int index, length;
Type(int index, int length) {
this.index = index;
this.length = length;
}
private static Map<Integer, Type> lookup = new TreeMap<>();
static {
for (Type t: Type.values())
lookup.put(t.index, t);
}
public static Type lookup(int t) {
if (!lookup.containsKey(t))
throw new IllegalStateException("Unknown Multihash type: "+t);
return lookup.get(t);
}
}
public final Type type;
private final byte[] hash;
public Multihash(Type type, byte[] hash) {
if (hash.length > 127)
throw new IllegalStateException("Unsupported hash size: "+hash.length);
if (hash.length != type.length)
throw new IllegalStateException("Incorrect hash length: " + hash.length + " != "+type.length);
this.type = type;
this.hash = hash;
}
public Multihash(Multihash toClone) {
this(toClone.type, toClone.hash); // N.B. despite being a byte[], hash is immutable
}
private Multihash(byte[] multihash) {
this(Type.lookup(multihash[0] & 0xff), Arrays.copyOfRange(multihash, 2, multihash.length));
}
private byte[] toBytes() {
byte[] res = new byte[hash.length+2];
res[0] = (byte)type.index;
res[1] = (byte)hash.length;
System.arraycopy(hash, 0, res, 2, hash.length);
return res;
}
public void serialize(DataOutput dout) throws IOException {
dout.write(toBytes());
}
public static Multihash deserialize(DataInput din) throws IOException {
int type = din.readUnsignedByte();
int len = din.readUnsignedByte();
Type t = Type.lookup(type);
byte[] hash = new byte[len];
din.readFully(hash);
return new Multihash(t, hash);
}
@Override
public String toString() {
return toBase58();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Multihash))
return false;
return type == ((Multihash) o).type && Arrays.equals(hash, ((Multihash) o).hash);
}
@Override
public int hashCode() {
return Arrays.hashCode(hash) ^ type.hashCode();
}
private final static char[] hexArray = "0123456789ABCDEF".toCharArray();
public String toHex() {
byte[] bytes = toBytes();
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
public String toBase58() {
return Base58.encode(toBytes());
}
public static Multihash fromHex(String hex) {
if (hex.length() % 2 != 0)
throw new IllegalStateException("Uneven number of hex digits!");
ByteArrayOutputStream bout = new ByteArrayOutputStream();
for (int i=0; i < hex.length()-1; i+= 2)
bout.write(Integer.valueOf(hex.substring(i, i+2), 16));
return new Multihash(bout.toByteArray());
}
public static Multihash fromBase58(String base58) {
return new Multihash(Base58.decode(base58));
}
}
| 3,624 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
PBKDF2Crypto.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/foundation/crypto/PBKDF2Crypto.java | package org.consenlabs.tokencore.foundation.crypto;
import org.consenlabs.tokencore.foundation.utils.NumericUtil;
import org.consenlabs.tokencore.wallet.model.Messages;
import org.consenlabs.tokencore.wallet.model.TokenException;
import org.spongycastle.crypto.digests.SHA256Digest;
import org.spongycastle.crypto.generators.PKCS5S2ParametersGenerator;
import org.spongycastle.crypto.params.KeyParameter;
/**
* Created by xyz on 2018/2/3.
*/
public final class PBKDF2Crypto extends Crypto<PBKDF2Params> {
static final String PBKDF2 = "pbkdf2";
PBKDF2Crypto() {
super();
this.kdf = PBKDF2;
}
public static PBKDF2Crypto createPBKDF2Crypto() {
PBKDF2Crypto crypto = new PBKDF2Crypto();
byte[] salt = NumericUtil.generateRandomBytes(SALT_LENGTH);
PBKDF2Params pbkdf2Params = PBKDF2Params.createPBKDF2Params();
pbkdf2Params.setSalt(NumericUtil.bytesToHex(salt));
crypto.kdfparams = pbkdf2Params;
return crypto;
}
@Override
public byte[] generateDerivedKey(byte[] password) {
PBKDF2Params params = this.kdfparams;
if (!PBKDF2Params.PRF.equals(params.getPrf())) {
throw new TokenException(Messages.PRF_UNSUPPORTED);
}
PKCS5S2ParametersGenerator generator = new PKCS5S2ParametersGenerator(new SHA256Digest());
generator.init(password, NumericUtil.hexToBytes(params.getSalt()), params.getC());
return ((KeyParameter) generator.generateDerivedParameters(256)).getKey();
}
}
| 1,495 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
KDFParams.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/foundation/crypto/KDFParams.java | package org.consenlabs.tokencore.foundation.crypto;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* Created by xyz on 2018/2/2.
*/
interface KDFParams {
int DK_LEN = 32;
int getDklen();
String getSalt();
@JsonIgnore
void validate();
}
| 283 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
SCryptParams.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/foundation/crypto/SCryptParams.java | package org.consenlabs.tokencore.foundation.crypto;
import com.google.common.base.Strings;
import org.consenlabs.tokencore.wallet.model.Messages;
import org.consenlabs.tokencore.wallet.model.TokenException;
/**
* Created by xyz on 2018/2/2.
*/
public class SCryptParams implements KDFParams {
static final int COST_FACTOR = 8192;
static final int BLOCK_SIZE_FACTOR = 8;
static final int PARALLELIZATION_FACTOR = 1;
private int dklen = 0;
private int n = 0;
private int p = 0;
private int r = 0;
private String salt;
public SCryptParams() {
}
public static SCryptParams createSCryptParams() {
SCryptParams params = new SCryptParams();
params.dklen = DK_LEN;
params.n = COST_FACTOR;
params.p = PARALLELIZATION_FACTOR;
params.r = BLOCK_SIZE_FACTOR;
return params;
}
public int getDklen() {
return dklen;
}
public void setDklen(int dklen) {
this.dklen = dklen;
}
public int getN() {
return n;
}
public void setN(int n) {
this.n = n;
}
public int getP() {
return p;
}
public void setP(int p) {
this.p = p;
}
public int getR() {
return r;
}
public void setR(int r) {
this.r = r;
}
public String getSalt() {
return salt;
}
@Override
public void validate() {
if (n == 0 || dklen == 0 || p == 0 || r == 0 || Strings.isNullOrEmpty(salt)) {
throw new TokenException(Messages.KDF_PARAMS_INVALID);
}
}
public void setSalt(String salt) {
this.salt = salt;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof SCryptParams)) {
return false;
}
SCryptParams that = (SCryptParams) o;
if (dklen != that.dklen) {
return false;
}
if (n != that.n) {
return false;
}
if (p != that.p) {
return false;
}
if (r != that.r) {
return false;
}
return getSalt() != null
? getSalt().equals(that.getSalt()) : that.getSalt() == null;
}
@Override
public int hashCode() {
int result = dklen;
result = 31 * result + n;
result = 31 * result + p;
result = 31 * result + r;
result = 31 * result + (getSalt() != null ? getSalt().hashCode() : 0);
return result;
}
}
| 2,389 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
SCryptCrypto.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/foundation/crypto/SCryptCrypto.java | package org.consenlabs.tokencore.foundation.crypto;
import com.lambdaworks.crypto.SCrypt;
import org.consenlabs.tokencore.foundation.utils.NumericUtil;
import org.consenlabs.tokencore.wallet.model.Messages;
import org.consenlabs.tokencore.wallet.model.TokenException;
import java.security.GeneralSecurityException;
/**
* Created by xyz on 2018/2/3.
*/
public class SCryptCrypto extends Crypto<SCryptParams> {
static final String SCRYPT = "scrypt";
public SCryptCrypto() {
super();
this.kdf = SCRYPT;
}
public static SCryptCrypto createSCryptCrypto() {
SCryptCrypto crypto = new SCryptCrypto();
byte[] salt = NumericUtil.generateRandomBytes(SALT_LENGTH);
SCryptParams params = SCryptParams.createSCryptParams();
params.setSalt(NumericUtil.bytesToHex(salt));
crypto.kdfparams = params;
return crypto;
}
@Override
public byte[] generateDerivedKey(byte[] password) {
int dkLen = this.kdfparams.getDklen();
int n = this.kdfparams.getN();
int p = this.kdfparams.getP();
int r = this.kdfparams.getR();
byte[] salt = NumericUtil.hexToBytes(this.kdfparams.getSalt());
try {
return SCrypt.scrypt(password, salt, n, r, p, dkLen);
} catch (GeneralSecurityException e) {
throw new TokenException(Messages.SCRYPT_PARAMS_INVALID, e);
}
}
}
| 1,374 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
ByteUtil.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/foundation/utils/ByteUtil.java | package org.consenlabs.tokencore.foundation.utils;
import java.util.Arrays;
public class ByteUtil {
private static byte[] trimLeadingBytes(byte[] bytes, byte b) {
int offset = 0;
for (; offset < bytes.length - 1; offset++) {
if (bytes[offset] != b) {
break;
}
}
return Arrays.copyOfRange(bytes, offset, bytes.length);
}
public static byte[] trimLeadingZeroes(byte[] bytes) {
return trimLeadingBytes(bytes, (byte) 0);
}
public static byte[] concat(byte[] b1, byte[] b2) {
byte[] result = Arrays.copyOf(b1, b1.length + b2.length);
System.arraycopy(b2, 0, result, b1.length, b2.length);
return result;
}
}
| 696 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
NumericUtil.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/foundation/utils/NumericUtil.java | package org.consenlabs.tokencore.foundation.utils;
import com.google.common.base.Strings;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.regex.Pattern;
public class NumericUtil {
private final static SecureRandom SECURE_RANDOM = new SecureRandom();
private static final String HEX_PREFIX = "0x";
public static byte[] generateRandomBytes(int size) {
byte[] bytes = new byte[size];
SECURE_RANDOM.nextBytes(bytes);
return bytes;
}
public static boolean isValidHex(String value) {
if (value == null) {
return false;
}
if (value.startsWith("0x") || value.startsWith("0X")) {
value = value.substring(2, value.length());
}
if (value.length() == 0 || value.length() % 2 != 0) {
return false;
}
String pattern = "[0-9a-fA-F]+";
return Pattern.matches(pattern, value);
// If TestRpc resolves the following issue, we can reinstate this code
// https://github.com/ethereumjs/testrpc/issues/220
// if (value.length() > 3 && value.charAt(2) == '0') {
// return false;
// }
}
public static String cleanHexPrefix(String input) {
if (hasHexPrefix(input)) {
return input.substring(2);
} else {
return input;
}
}
public static String prependHexPrefix(String input) {
if (input.length() > 1 && !hasHexPrefix(input)) {
return HEX_PREFIX + input;
} else {
return input;
}
}
private static boolean hasHexPrefix(String input) {
return input.length() > 1 && input.charAt(0) == '0' && input.charAt(1) == 'x';
}
public static BigInteger bytesToBigInteger(byte[] value, int offset, int length) {
return bytesToBigInteger((Arrays.copyOfRange(value, offset, offset + length)));
}
public static BigInteger bytesToBigInteger(byte[] value) {
return new BigInteger(1, value);
}
public static BigInteger hexToBigInteger(String hexValue) {
String cleanValue = cleanHexPrefix(hexValue);
return new BigInteger(cleanValue, 16);
}
public static String bigIntegerToHex(BigInteger value) {
return value.toString(16);
}
public static String bigIntegerToHexWithZeroPadded(BigInteger value, int size) {
String result = bigIntegerToHex(value);
int length = result.length();
if (length > size) {
throw new UnsupportedOperationException(
"Value " + result + "is larger then length " + size);
} else if (value.signum() < 0) {
throw new UnsupportedOperationException("Value cannot be negative");
}
if (length < size) {
result = Strings.repeat("0", size - length) + result;
}
return result;
}
public static byte[] bigIntegerToBytesWithZeroPadded(BigInteger value, int length) {
byte[] result = new byte[length];
byte[] bytes = value.toByteArray();
int bytesLength;
int srcOffset;
if (bytes[0] == 0) {
bytesLength = bytes.length - 1;
srcOffset = 1;
} else {
bytesLength = bytes.length;
srcOffset = 0;
}
if (bytesLength > length) {
throw new RuntimeException("Input is too large to put in byte array of size " + length);
}
int destOffset = length - bytesLength;
System.arraycopy(bytes, srcOffset, result, destOffset, bytesLength);
return result;
}
public static byte[] hexToBytes(String input) {
String cleanInput = cleanHexPrefix(input);
int len = cleanInput.length();
if (len == 0) {
return new byte[]{};
}
byte[] data;
int startIdx;
if (len % 2 != 0) {
data = new byte[(len / 2) + 1];
data[0] = (byte) Character.digit(cleanInput.charAt(0), 16);
startIdx = 1;
} else {
data = new byte[len / 2];
startIdx = 0;
}
for (int i = startIdx; i < len; i += 2) {
data[(i + 1) / 2] = (byte) ((Character.digit(cleanInput.charAt(i), 16) << 4)
+ Character.digit(cleanInput.charAt(i + 1), 16));
}
return data;
}
public static byte[] hexToBytesLittleEndian(String input) {
byte[] bytes = hexToBytes(input);
if (ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN) {
return bytes;
}
int middle = bytes.length / 2;
for (int i = 0; i < middle; i++) {
byte b = bytes[i];
bytes[i] = bytes[bytes.length - 1 - i];
bytes[bytes.length - 1 - i] = b;
}
return bytes;
}
public static byte[] reverseBytes(byte[] bytes) {
int middle = bytes.length / 2;
for (int i = 0; i < middle; i++) {
byte b = bytes[i];
bytes[i] = bytes[bytes.length - 1 - i];
bytes[bytes.length - 1 - i] = b;
}
return bytes;
}
public static String bytesToHex(byte[] input) {
StringBuilder stringBuilder = new StringBuilder();
if (input.length == 0) {
return "";
}
for (byte anInput : input) {
stringBuilder.append(String.format("%02x", anInput));
}
return stringBuilder.toString();
}
public static String beBigEndianHex(String hex) {
if (ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN) {
return hex;
}
return reverseHex(hex);
}
public static String beLittleEndianHex(String hex) {
if (ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN) {
return hex;
}
return reverseHex(hex);
}
private static String reverseHex(String hex) {
byte[] bytes = hexToBytes(hex);
bytes = reverseBytes(bytes);
return bytesToHex(bytes);
}
public static int bytesToInt(byte[] bytes) {
return ByteBuffer.wrap(bytes).getInt();
}
public static byte[] intToBytes(int intValue) {
byte[] intBytes = ByteBuffer.allocate(4).putInt(intValue).array();
int zeroLen = 0;
for (byte b : intBytes) {
if (b != 0) {
break;
}
zeroLen++;
}
if (zeroLen == 4) {
zeroLen = 3;
}
return Arrays.copyOfRange(intBytes, zeroLen, intBytes.length);
}
}
| 6,183 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
MnemonicUtil.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/foundation/utils/MnemonicUtil.java | package org.consenlabs.tokencore.foundation.utils;
import com.google.common.base.Joiner;
import org.bitcoinj.crypto.MnemonicCode;
import org.consenlabs.tokencore.wallet.model.Messages;
import org.consenlabs.tokencore.wallet.model.TokenException;
import java.util.List;
public class MnemonicUtil {
public static void validateMnemonics(List<String> mnemonicCodes) {
try {
MnemonicCode.INSTANCE.check(mnemonicCodes);
} catch (org.bitcoinj.crypto.MnemonicException.MnemonicLengthException e) {
throw new TokenException(Messages.MNEMONIC_INVALID_LENGTH);
} catch (org.bitcoinj.crypto.MnemonicException.MnemonicWordException e) {
throw new TokenException(Messages.MNEMONIC_BAD_WORD);
} catch (Exception e) {
throw new TokenException(Messages.MNEMONIC_CHECKSUM);
}
}
public static List<String> randomMnemonicCodes() {
return toMnemonicCodes(NumericUtil.generateRandomBytes(16));
}
public static String randomMnemonicStr() {
List<String> mnemonicCodes=randomMnemonicCodes();
return Joiner.on(" ").join(mnemonicCodes);
}
public static List<String> toMnemonicCodes(byte[] entropy) {
try {
return MnemonicCode.INSTANCE.toMnemonic(entropy);
} catch (org.bitcoinj.crypto.MnemonicException.MnemonicLengthException e) {
throw new TokenException(Messages.MNEMONIC_INVALID_LENGTH);
} catch (Exception e) {
throw new TokenException(Messages.MNEMONIC_CHECKSUM);
}
}
}
| 1,506 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
CachedDerivedKey.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/foundation/utils/CachedDerivedKey.java | package org.consenlabs.tokencore.foundation.utils;
import org.consenlabs.tokencore.foundation.crypto.Hash;
public class CachedDerivedKey {
private String hashedPassword;
private byte[] derivedKey;
public CachedDerivedKey(String password, byte[] derivedKey) {
this.hashedPassword = hash(password);
this.derivedKey = derivedKey;
}
private String hash(String password) {
return NumericUtil.bytesToHex(Hash.sha256(Hash.sha256(password.getBytes())));
}
public byte[] getDerivedKey(String password) {
if (hashedPassword != null && hashedPassword.equals(hash(password))) {
return derivedKey;
}
return null;
}
}
| 681 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
MetaUtil.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/foundation/utils/MetaUtil.java | package org.consenlabs.tokencore.foundation.utils;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.params.TestNet3Params;
import org.consenlabs.tokencore.wallet.model.ChainType;
import org.consenlabs.tokencore.wallet.model.Metadata;
import org.consenlabs.tokencore.wallet.network.*;
/**
* Created by pie on 2018/12/5 15: 32.
*/
public class MetaUtil {
public static NetworkParameters getNetWork(Metadata metadata) {
NetworkParameters network = null;
if (metadata.getChainType() == null) return MainNetParams.get();
switch (metadata.getChainType()) {
case ChainType.LITECOIN:
network = LitecoinMainNetParams.get();
break;
case ChainType.BITCOIN:
network = metadata.isMainNet() ? MainNetParams.get() : TestNet3Params.get();
break;
case ChainType.DASH:
network = DashMainNetParams.get();
break;
case ChainType.BITCOINCASH:
network = BitcoinCashMainNetParams.get();
break;
case ChainType.BITCOINSV:
network = BitcoinSvMainNetParams.get();
break;
case ChainType.DOGECOIN:
network = DogecoinMainNetParams.get();
break;
}
return network;
}
}
| 1,448 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
DateUtil.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/foundation/utils/DateUtil.java | package org.consenlabs.tokencore.foundation.utils;
import java.util.Calendar;
import java.util.TimeZone;
public class DateUtil {
public static long getUTCTime() {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
return cal.getTimeInMillis()/1000;
}
}
| 293 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
RlpEncoder.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/foundation/rlp/RlpEncoder.java | package org.consenlabs.tokencore.foundation.rlp;
import org.consenlabs.tokencore.foundation.utils.ByteUtil;
import java.util.Arrays;
import java.util.List;
/**
* <p>Recursive Length Prefix (RLP) encoder.</p>
*
* <p>For the specification, refer to p16 of the <a href="http://gavwood.com/paper.pdf">
* yellow paper</a> and <a href="https://github.com/ethereum/wiki/wiki/RLP">here</a>.</p>
*/
public class RlpEncoder {
private static final int STRING_OFFSET = 0x80;
private static final int LIST_OFFSET = 0xc0;
public static byte[] encode(RlpType value) {
if (value instanceof RlpString) {
return encodeString((RlpString) value);
} else {
return encodeList((RlpList) value);
}
}
private static byte[] encode(byte[] bytesValue, int offset) {
if (bytesValue.length == 1
&& offset == STRING_OFFSET
&& bytesValue[0] >= (byte) 0x00
&& bytesValue[0] <= (byte) 0x7f) {
return bytesValue;
} else if (bytesValue.length <= 55) {
byte[] result = new byte[bytesValue.length + 1];
result[0] = (byte) (offset + bytesValue.length);
System.arraycopy(bytesValue, 0, result, 1, bytesValue.length);
return result;
} else {
byte[] encodedStringLength = toMinimalByteArray(bytesValue.length);
byte[] result = new byte[bytesValue.length + encodedStringLength.length + 1];
result[0] = (byte) ((offset + 0x37) + encodedStringLength.length);
System.arraycopy(encodedStringLength, 0, result, 1, encodedStringLength.length);
System.arraycopy(
bytesValue, 0, result, encodedStringLength.length + 1, bytesValue.length);
return result;
}
}
private static byte[] encodeString(RlpString value) {
return encode(value.getBytes(), STRING_OFFSET);
}
private static byte[] toMinimalByteArray(int value) {
byte[] encoded = toByteArray(value);
for (int i = 0; i < encoded.length; i++) {
if (encoded[i] != 0) {
return Arrays.copyOfRange(encoded, i, encoded.length);
}
}
return new byte[]{ };
}
private static byte[] toByteArray(int value) {
return new byte[] {
(byte) ((value >> 24) & 0xff),
(byte) ((value >> 16) & 0xff),
(byte) ((value >> 8) & 0xff),
(byte) (value & 0xff)
};
}
private static byte[] encodeList(RlpList value) {
List<RlpType> values = value.getValues();
if (values.isEmpty()) {
return encode(new byte[]{ }, LIST_OFFSET);
} else {
byte[] result = new byte[0];
for (RlpType entry:values) {
result = ByteUtil.concat(result, encode(entry));
}
return encode(result, LIST_OFFSET);
}
}
}
| 3,065 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
RlpList.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/foundation/rlp/RlpList.java | package org.consenlabs.tokencore.foundation.rlp;
import java.util.Arrays;
import java.util.List;
/**
* RLP list type.
*/
public class RlpList implements RlpType {
private final List<RlpType> values;
public RlpList(RlpType... values) {
this.values = Arrays.asList(values);
}
public RlpList(List<RlpType> values) {
this.values = values;
}
public List<RlpType> getValues() {
return values;
}
}
| 473 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
RlpString.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/foundation/rlp/RlpString.java | package org.consenlabs.tokencore.foundation.rlp;
import java.math.BigInteger;
import java.util.Arrays;
/**
* RLP string type.
*/
public class RlpString implements RlpType {
private static final byte[] EMPTY = new byte[]{ };
private final byte[] value;
private RlpString(byte[] value) {
this.value = value;
}
public byte[] getBytes() {
return value;
}
public static RlpString create(byte[] value) {
return new RlpString(value);
}
public static RlpString create(byte value) {
return new RlpString(new byte[]{ value });
}
public static RlpString create(BigInteger value) {
// RLP encoding only supports positive integer values
if (value.signum() < 1) {
return new RlpString(EMPTY);
} else {
byte[] bytes = value.toByteArray();
if (bytes[0] == 0) { // remove leading zero
return new RlpString(Arrays.copyOfRange(bytes, 1, bytes.length));
} else {
return new RlpString(bytes);
}
}
}
public static RlpString create(long value) {
return create(BigInteger.valueOf(value));
}
public static RlpString create(String value) {
return new RlpString(value.getBytes());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RlpString rlpString = (RlpString) o;
return Arrays.equals(value, rlpString.value);
}
@Override
public int hashCode() {
return Arrays.hashCode(value);
}
}
| 1,778 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
RlpType.java | /FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/main/java/org/consenlabs/tokencore/foundation/rlp/RlpType.java | package org.consenlabs.tokencore.foundation.rlp;
/**
* Base RLP type.
*/
public interface RlpType {
}
| 112 | Java | .java | GalaxySciTech/tokencore | 418 | 38 | 5 | 2019-01-22T10:30:29Z | 2023-12-25T03:34:34Z |
ClassificationModule.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-classification-ui/src/main/java/org/esa/snap/classification/ClassificationModule.java | /*
* Copyright (C) 2016 by Array Systems Computing Inc. http://www.array.ca
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.classification;
import org.esa.snap.engine_utilities.util.ResourceUtils;
import org.openide.modules.OnStart;
/**
* Handle OnStart for module
*/
public class ClassificationModule {
@OnStart
public static class StartOp implements Runnable {
@Override
public void run() {
ResourceUtils.installGraphs(this.getClass(), "org/esa/snap/classification/graphs/");
}
}
}
| 1,157 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
BaseClassifierOpUI.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-classification-ui/src/main/java/org/esa/snap/classification/gpf/ui/BaseClassifierOpUI.java | /*
* Copyright (C) 2016 by Array Systems Computing Inc. http://www.array.ca
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.classification.gpf.ui;
import org.esa.snap.classification.gpf.BaseClassifier;
import org.esa.snap.core.datamodel.ProductNodeGroup;
import org.esa.snap.core.datamodel.VectorDataNode;
import org.esa.snap.engine_utilities.util.VectorUtils;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.core.util.io.FileUtils;
import org.esa.snap.graphbuilder.gpf.ui.BaseOperatorUI;
import org.esa.snap.graphbuilder.gpf.ui.OperatorUIUtils;
import org.esa.snap.graphbuilder.gpf.ui.UIValidation;
import org.esa.snap.graphbuilder.rcp.utils.DialogUtils;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.AppContext;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.io.FileFilter;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* User interface for classifiers
*/
public abstract class BaseClassifierOpUI extends BaseOperatorUI {
private final JRadioButton loadBtn = new JRadioButton("Load and apply classifier", false);
private final JRadioButton trainBtn = new JRadioButton("Train and apply classifier", true);
private final JComboBox<String> classifierNameComboBox = new JComboBox();
private final JButton deleteClassiferBtn = new JButton("X");
private final JTextField newClassifierNameField = new JTextField("newClassifier");
private final JRadioButton trainOnRasterBtn = new JRadioButton("Train on Raster", false);
private final JRadioButton trainOnVectorsBtn = new JRadioButton("Train on Vectors", true);
private final JTextField numTrainSamples = new JTextField("");
private final JCheckBox evaluateClassifier = new JCheckBox("");
private final JCheckBox evaluateFeaturePowerSet = new JCheckBox("");
private final JTextField minPowerSetSize = new JTextField("");
private final JTextField maxPowerSetSize = new JTextField("");
private final JCheckBox doClassValQuantization = new JCheckBox();
private final JTextField minClassValue = new JTextField("");
private final JTextField classValStepSize = new JTextField("");
private final JTextField classLevels = new JTextField("");
private final JLabel maxClassValue = new JLabel("");
private final JRadioButton labelSourceVectorName = new JRadioButton("Vector node name", true);
private final JRadioButton labelSourceAttribute = new JRadioButton("Attribute value", false); // not used
private final JList<String> trainingBands = new JList();
private final JList<String> trainingVectors = new JList();
private final JList<String> featureBandNames = new JList();
protected JPanel classifierPanel, rasterPanel, vectorPanel, featurePanel;
protected GridBagConstraints classifiergbc;
private final String classifierType;
public BaseClassifierOpUI(final String classifierType) {
this.classifierType = classifierType;
}
@Override
public JComponent CreateOpTab(String operatorName, Map<String, Object> parameterMap, AppContext appContext) {
initializeOperatorUI(operatorName, parameterMap);
final JComponent panel = createPanel();
doClassValQuantization.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
enableQuantization(doClassValQuantization.isSelected());
}
});
minClassValue.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateMaxClassValue();
}
});
classValStepSize.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateMaxClassValue();
}
});
classLevels.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateMaxClassValue();
}
});
evaluateClassifier.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
enablePowerSet();
}
});
evaluateFeaturePowerSet.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
enablePowerSet();
}
});
loadBtn.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
boolean doTraining = e.getStateChange() != ItemEvent.SELECTED;
enableTraining(doTraining);
enableTrainOnRaster(doTraining, trainOnRasterBtn.isSelected());
}
});
labelSourceAttribute.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
final AttributeDialog dlg = new AttributeDialog("Labels from Attribute",
VectorUtils.getAttributesList(sourceProducts), null);
dlg.show();
if (dlg.IsOK()) {
labelSourceAttribute.setText(dlg.getValue());
}
}
}
});
populateClassifierNames();
classifierNameComboBox.setEditable(false);
classifierNameComboBox.setMaximumRowCount(5);
deleteClassiferBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
requestDeleteClassifier();
}
});
trainingBands.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
trainingVectors.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
trainOnRasterBtn.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
enableTrainOnRaster(trainBtn.isSelected(), e.getStateChange() == ItemEvent.SELECTED);
}
});
initParameters();
return new JScrollPane(panel);
}
private Path getClassifierFolder() {
return SystemUtils.getAuxDataPath().
resolve(BaseClassifier.CLASSIFIER_ROOT_FOLDER).resolve(classifierType);
}
private void populateClassifierNames() {
final Path classifierDir = getClassifierFolder();
final File folder = new File(classifierDir.toString());
final File[] listOfFiles = folder.listFiles(new FileFilter() {
public boolean accept(File pathname) {
return pathname.isFile() && pathname.getName().endsWith(BaseClassifier.CLASSIFIER_FILE_EXTENSION);
}
});
if (listOfFiles != null && listOfFiles.length > 0) {
for (File file : listOfFiles) {
classifierNameComboBox.addItem(FileUtils.getFilenameWithoutExtension(file));
}
classifierNameComboBox.setSelectedIndex(0);
} else {
trainBtn.setSelected(true);
}
}
private void requestDeleteClassifier() {
String name = (String) classifierNameComboBox.getSelectedItem();
if (name != null) {
Dialogs.Answer answer = Dialogs.requestDecision("Delete Classifier",
"Are you sure you want to delete classifier " + name,
true, null);
if (answer.equals(Dialogs.Answer.YES)) {
final Path classifierDir = getClassifierFolder();
final File classiferFile = classifierDir.resolve(name + BaseClassifier.CLASSIFIER_FILE_EXTENSION).toFile();
if (classiferFile.exists()) {
if (deleteClassifier(classiferFile, name)) {
classifierNameComboBox.removeItem(name);
if (classifierNameComboBox.getItemCount() == 0) {
trainBtn.setSelected(true);
}
} else {
Dialogs.showError("Unable to delete classifier " + classiferFile);
}
} else {
Dialogs.showError("Unable to find classifier " + classiferFile);
}
}
}
}
private static boolean deleteClassifier(final File classifierFile, final String classifierName) {
boolean ok = classifierFile.delete();
// find other associated files
final File[] files = classifierFile.getParentFile().listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return FileUtils.getFilenameWithoutExtension(pathname).equals(classifierName);
}
});
if (files != null) {
for (File file : files) {
file.delete();
}
}
return ok;
}
protected abstract void setEnabled(final boolean enabled);
private void enablePowerSet() {
final boolean evalEnabled = evaluateClassifier.isEnabled() && evaluateClassifier.isSelected();
evaluateFeaturePowerSet.setEnabled(evalEnabled);
final boolean psEnabled = evaluateFeaturePowerSet.isSelected();
minPowerSetSize.setEnabled(evalEnabled && psEnabled);
maxPowerSetSize.setEnabled(evalEnabled && psEnabled);
}
private void enableTrainOnRaster(final boolean doTraining, final boolean trainOnRaster) {
//System.out.println("BaseClassifierOpUI.enableTrainOnRaster: doTraining = " + doTraining + " trainOnRaster = " + trainOnRaster);
if (doTraining) {
if (trainOnRaster) {
OperatorUIUtils.initParamList(trainingBands, getTrainingBands());
} else {
OperatorUIUtils.initParamList(trainingVectors, getPolygons());
}
}
rasterPanel.setVisible(doTraining && trainOnRaster);
vectorPanel.setVisible(doTraining && !trainOnRaster);
featurePanel.setVisible(doTraining);
}
private void enableQuantization(final boolean enable) {
minClassValue.setEnabled(enable);
classValStepSize.setEnabled(enable);
classLevels.setEnabled(enable);
maxClassValue.setEnabled(enable);
}
private void setEnableDoClassValQuantization(final boolean enable) {
doClassValQuantization.setEnabled(enable);
minClassValue.setEnabled(enable && doClassValQuantization.isSelected());
classValStepSize.setEnabled(enable && doClassValQuantization.isSelected());
classLevels.setEnabled(enable && doClassValQuantization.isSelected());
maxClassValue.setEnabled(enable && doClassValQuantization.isSelected());
}
private void enableTraining(boolean doTraining) {
classifierNameComboBox.setEnabled(!doTraining);
deleteClassiferBtn.setEnabled(!doTraining);
newClassifierNameField.setEnabled(doTraining);
setEnableDoClassValQuantization(doTraining);
trainOnRasterBtn.setEnabled(doTraining);
trainOnVectorsBtn.setEnabled(doTraining);
numTrainSamples.setEnabled(doTraining);
trainingBands.setEnabled(doTraining);
if (!trainingBands.isEnabled()) {
trainingBands.clearSelection();
}
trainingVectors.setEnabled(doTraining);
if (!trainingVectors.isEnabled()) {
trainingVectors.clearSelection();
}
featureBandNames.setEnabled(doTraining);
evaluateClassifier.setEnabled(doTraining);
evaluateFeaturePowerSet.setEnabled(doTraining);
setEnabled(doTraining);
}
private void updateMaxClassValue() {
final double minVal = Double.parseDouble(minClassValue.getText());
final double stepSize = Double.parseDouble(classValStepSize.getText());
final int levels = Integer.parseInt(classLevels.getText());
final double maxClassVal = BaseClassifier.getMaxValue(minVal, stepSize, levels);
maxClassValue.setText(String.valueOf(maxClassVal));
}
@Override
public void initParameters() {
String newClassifierName = (String) paramMap.get("savedClassifierName");
if (DialogUtils.contains(classifierNameComboBox, newClassifierName)) {
classifierNameComboBox.setSelectedItem(newClassifierName);
}
String numSamples = String.valueOf(paramMap.get("numTrainSamples"));
numTrainSamples.setText(numSamples);
Boolean eval = (Boolean) (paramMap.get("evaluateClassifier"));
if (eval != null) {
evaluateClassifier.setSelected(eval);
}
Boolean evalPS = (Boolean) (paramMap.get("evaluateFeaturePowerSet"));
if (evalPS != null) {
evaluateFeaturePowerSet.setSelected(evalPS);
}
Integer minPS = (Integer) (paramMap.get("minPowerSetSize"));
if (minPS != null) {
minPowerSetSize.setText(String.valueOf(minPS));
}
Integer maxPS = (Integer) (paramMap.get("maxPowerSetSize"));
if (maxPS != null) {
maxPowerSetSize.setText(String.valueOf(maxPS));
}
Boolean doQuant = (Boolean) (paramMap.get("doClassValQuantization"));
if (doQuant != null) {
doClassValQuantization.setSelected(doQuant);
}
minClassValue.setText(String.valueOf(paramMap.get("minClassValue")));
classValStepSize.setText(String.valueOf(paramMap.get("classValStepSize")));
classLevels.setText(String.valueOf(paramMap.get("classLevels")));
final Double minVal = (Double) paramMap.get("minClassValue");
final Double stepSize = (Double) paramMap.get("classValStepSize");
final Integer levels = (Integer) paramMap.get("classLevels");
if(minVal != null && stepSize != null && levels != null) {
final double maxClassVal = BaseClassifier.getMaxValue(minVal, stepSize, levels);
maxClassValue.setText(String.valueOf(maxClassVal));
}
Boolean trainOnRastersVal = (Boolean) paramMap.get("trainOnRaster");
boolean trainOnRasters = trainOnRastersVal != null && trainOnRastersVal;
trainOnRasterBtn.setSelected(trainOnRasters);
String labelSource = (String) paramMap.get("labelSource");
if (labelSource == null || labelSource.equals(BaseClassifier.VectorNodeNameLabelSource)) {
labelSourceVectorName.setSelected(true);
}
boolean doTraining = trainBtn.isSelected();
enableTraining(doTraining);
enableTrainOnRaster(doTraining, trainOnRasters);
enablePowerSet();
paramMap.put("bandsOrVectors", null);
OperatorUIUtils.initParamList(featureBandNames, getFeatures());
}
@Override
public UIValidation validateParameters() {
if (!loadBtn.isSelected()) {
if (DialogUtils.contains(classifierNameComboBox, newClassifierNameField.getText())) {
// return new UIValidation(UIValidation.State.ERROR, "Name already in use. Please select a unique classifier name");
}
}
return new UIValidation(UIValidation.State.OK, "");
}
@Override
public void updateParameters() {
//System.out.println("BaseClassifierOpUI.updateParameters: called");
paramMap.put("numTrainSamples", Integer.parseInt(numTrainSamples.getText()));
paramMap.put("evaluateClassifier", evaluateClassifier.isSelected());
paramMap.put("evaluateFeaturePowerSet", evaluateFeaturePowerSet.isSelected());
if(evaluateClassifier.isSelected() && evaluateFeaturePowerSet.isSelected()) {
if(!minPowerSetSize.getText().isEmpty()) {
paramMap.put("minPowerSetSize", Integer.parseInt(minPowerSetSize.getText()));
}
if(!maxPowerSetSize.getText().isEmpty()) {
paramMap.put("maxPowerSetSize", Integer.parseInt(maxPowerSetSize.getText()));
}
}
paramMap.put("doLoadClassifier", loadBtn.isSelected());
paramMap.put("doClassValQuantization", doClassValQuantization.isSelected());
paramMap.put("minClassValue", Double.parseDouble(minClassValue.getText()));
paramMap.put("classValStepSize", Double.parseDouble(classValStepSize.getText()));
paramMap.put("classLevels", Integer.parseInt(classLevels.getText()));
paramMap.put("trainOnRaster", trainOnRasterBtn.isSelected());
String classifierName = loadBtn.isSelected() ?
(String) classifierNameComboBox.getSelectedItem() :
newClassifierNameField.getText();
paramMap.put("savedClassifierName", classifierName);
if (labelSourceAttribute.isSelected()) {
paramMap.put("labelSource", labelSourceAttribute.getText());
} else {
paramMap.put("labelSource", BaseClassifier.VectorNodeNameLabelSource);
}
updateParamList(trainingBands, paramMap, "trainingBands");
//dumpSelectedValues("trainingBands", trainingBands);
updateParamList(trainingVectors, paramMap, "trainingVectors");
//dumpSelectedValues("trainingVectors", trainingVectors);
updateParamList(featureBandNames, paramMap, "featureBands");
//dumpSelectedValues("features", featureBandNames);
}
private static void dumpSelectedValues(final String name, final JList<String> paramList) {
SystemUtils.LOG.info(name + " selected values:");
final List<String> selectedValues = paramList.getSelectedValuesList();
for (Object selectedValue : selectedValues) {
SystemUtils.LOG.info(' ' + (String) selectedValue);
}
}
private static void updateParamList(final JList paramList, final Map<String, Object> paramMap, final String paramName) {
final List selectedValues = paramList.getSelectedValuesList();
final String names[] = new String[selectedValues.size()];
int i = 0;
for (Object selectedValue : selectedValues) {
names[i++] = (String) selectedValue;
}
if (names.length == 0 && paramMap.get(paramName) != null) {
// Remove previously selected values, so that nothing is selected
paramMap.remove(paramName);
} else {
// Replace previously selected values
paramMap.put(paramName, names);
}
}
protected JPanel createPanel() {
final JPanel contentPane = new JPanel();
contentPane.setLayout(new GridBagLayout());
GridBagConstraints gbc = DialogUtils.createGridBagConstraints();
classifierPanel = createClassifierPanel();
gbc.gridy++;
contentPane.add(classifierPanel, gbc);
rasterPanel = createRasterPanel();
gbc.gridy++;
contentPane.add(rasterPanel, gbc);
vectorPanel = createVectorPanel();
contentPane.add(vectorPanel, gbc);
featurePanel = createFeaturePanel();
gbc.gridy++;
contentPane.add(featurePanel, gbc);
DialogUtils.fillPanel(contentPane, gbc);
enablePowerSet();
return contentPane;
}
private JPanel createClassifierPanel() {
final JPanel classifierPanel = new JPanel();
classifierPanel.setLayout(new GridBagLayout());
classifierPanel.setBorder(new TitledBorder("Classifier"));
classifiergbc = DialogUtils.createGridBagConstraints();
final ButtonGroup group1 = new ButtonGroup();
group1.add(trainBtn);
group1.add(loadBtn);
classifierPanel.add(trainBtn, classifiergbc);
classifiergbc.gridx = 1;
classifierPanel.add(newClassifierNameField, classifiergbc);
classifiergbc.gridx = 0;
classifiergbc.gridx = 0;
classifiergbc.gridy++;
classifierPanel.add(loadBtn, classifiergbc);
classifiergbc.gridx = 1;
classifierPanel.add(classifierNameComboBox, classifiergbc);
classifiergbc.gridx = 2;
classifierPanel.add(deleteClassiferBtn, classifiergbc);
final ButtonGroup group2 = new ButtonGroup();
group2.add(trainOnRasterBtn);
group2.add(trainOnVectorsBtn);
final JPanel radioPanel = new JPanel(new FlowLayout());
radioPanel.add(trainOnRasterBtn);
radioPanel.add(trainOnVectorsBtn);
classifiergbc.gridy++;
classifiergbc.gridx = 1;
classifierPanel.add(radioPanel, classifiergbc);
classifiergbc.gridx = 0;
classifiergbc.gridy++;
DialogUtils.addComponent(classifierPanel, classifiergbc, "Evaluate classifier", evaluateClassifier);
classifiergbc.gridy++;
DialogUtils.addComponent(classifierPanel, classifiergbc, "Evaluate Feature Power Set", evaluateFeaturePowerSet);
classifiergbc.gridy++;
final JPanel powerSetPanel = new JPanel(new FlowLayout());
minPowerSetSize.setColumns(4);
maxPowerSetSize.setColumns(4);
powerSetPanel.add(new JLabel("Min Power Set Size:"));
powerSetPanel.add(minPowerSetSize);
powerSetPanel.add(new JLabel("Max Power Set Size:"));
powerSetPanel.add(maxPowerSetSize);
classifiergbc.gridy++;
classifiergbc.gridx = 1;
classifierPanel.add(powerSetPanel, classifiergbc);
classifiergbc.gridx = 0;
classifiergbc.gridy++;
DialogUtils.addComponent(classifierPanel, classifiergbc, "Number of training samples", numTrainSamples);
DialogUtils.fillPanel(classifierPanel, classifiergbc);
return classifierPanel;
}
private JPanel createRasterPanel() {
final JPanel rasterPanel = new JPanel();
rasterPanel.setLayout(new GridBagLayout());
rasterPanel.setBorder(new TitledBorder("Raster Training"));
GridBagConstraints gbc = DialogUtils.createGridBagConstraints();
gbc.gridy++;
DialogUtils.addComponent(rasterPanel, gbc, "Quantize class value", doClassValQuantization);
gbc.gridy++;
DialogUtils.addComponent(rasterPanel, gbc, "Min class value", minClassValue);
gbc.gridy++;
DialogUtils.addComponent(rasterPanel, gbc, "Class value step size", classValStepSize);
gbc.gridy++;
DialogUtils.addComponent(rasterPanel, gbc, "Class levels", classLevels);
gbc.gridy++;
DialogUtils.addComponent(rasterPanel, gbc, "Max class value", maxClassValue);
gbc.gridy++;
DialogUtils.addComponent(rasterPanel, gbc, "Training band:", new JScrollPane(trainingBands));
DialogUtils.fillPanel(rasterPanel, gbc);
return rasterPanel;
}
private JPanel createVectorPanel() {
final JPanel vectorPanel = new JPanel();
vectorPanel.setLayout(new GridBagLayout());
vectorPanel.setBorder(new TitledBorder("Vector Training"));
GridBagConstraints gbc = DialogUtils.createGridBagConstraints();
gbc.gridy++;
DialogUtils.addComponent(vectorPanel, gbc, "Training vectors: ", new JScrollPane(trainingVectors));
gbc.gridy++;
gbc.gridx = 0;
//vectorPanel.add(new JLabel("Labels:"), gbc);
//final ButtonGroup group3 = new ButtonGroup();
//group3.add(labelSourceVectorName);
//group3.add(labelSourceAttribute);
//JPanel radioPanel = new JPanel(new FlowLayout());
//radioPanel.add(labelSourceVectorName);
//radioPanel.add(labelSourceAttribute);
gbc.gridx = 1;
//vectorPanel.add(radioPanel, gbc);
DialogUtils.fillPanel(vectorPanel, gbc);
return vectorPanel;
}
private JPanel createFeaturePanel() {
final JPanel featurePanel = new JPanel();
featurePanel.setBorder(new TitledBorder("Feature Selection"));
featurePanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = DialogUtils.createGridBagConstraints();
DialogUtils.addComponent(featurePanel, gbc, "Feature bands: ", new JScrollPane(featureBandNames));
DialogUtils.fillPanel(featurePanel, gbc);
return featurePanel;
}
private String[] getPolygons() {
// Get polygons from the first product which is assumed to be maskProduct in BaseClassifier
final ArrayList<String> geometryNames = new ArrayList<>(5);
if (sourceProducts != null) {
if (sourceProducts.length > 1) {
final ProductNodeGroup<VectorDataNode> vectorDataNodes = sourceProducts[0].getVectorDataGroup();
for(int i=0; i< vectorDataNodes.getNodeCount(); ++i) {
VectorDataNode node = vectorDataNodes.get(i);
if(!node.getFeatureCollection().isEmpty()) {
geometryNames.add(node.getName() + "::" + sourceProducts[0].getName());
}
}
} else {
final ProductNodeGroup<VectorDataNode> vectorDataNodes = sourceProducts[0].getVectorDataGroup();
for(int i=0; i< vectorDataNodes.getNodeCount(); ++i) {
VectorDataNode node = vectorDataNodes.get(i);
if(!node.getFeatureCollection().isEmpty()) {
geometryNames.add(node.getName());
}
}
}
}
return geometryNames.toArray(new String[geometryNames.size()]);
}
private String[] getTrainingBands() {
final ArrayList<String> bandNames = new ArrayList<>(5);
if (sourceProducts != null) {
if (sourceProducts.length > 1) {
for (String name : sourceProducts[0].getBandNames()) {
bandNames.add(name + "::" + sourceProducts[0].getName());
}
} else {
bandNames.addAll(Arrays.asList(sourceProducts[0].getBandNames()));
}
}
return bandNames.toArray(new String[bandNames.size()]);
}
private String[] getFeatures() {
final ArrayList<String> featureNames = new ArrayList<>(5);
if (sourceProducts != null) {
for (Product prod : sourceProducts) {
for (String name : prod.getBandNames()) {
if (BaseClassifier.excludeBand(name))
continue;
if (sourceProducts.length > 1) {
featureNames.add(name + "::" + prod.getName());
} else {
featureNames.add(name);
}
}
}
}
return featureNames.toArray(new String[featureNames.size()]);
}
}
| 27,839 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SVMClassifierOpUI.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-classification-ui/src/main/java/org/esa/snap/classification/gpf/ui/SVMClassifierOpUI.java | /*
* Copyright (C) 2016 by Array Systems Computing Inc. http://www.array.ca
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.classification.gpf.ui;
import org.esa.snap.classification.gpf.svm.SVMClassifierOp;
/**
* User interface for SVM
*/
public class SVMClassifierOpUI extends BaseClassifierOpUI {
public SVMClassifierOpUI() {
super(SVMClassifierOp.CLASSIFIER_TYPE);
}
@Override
protected void setEnabled(final boolean enabled) {}
}
| 1,084 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
KDTreeKNNClassifierOpUI.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-classification-ui/src/main/java/org/esa/snap/classification/gpf/ui/KDTreeKNNClassifierOpUI.java | /*
* Copyright (C) 2016 by Array Systems Computing Inc. http://www.array.ca
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.classification.gpf.ui;
import org.esa.snap.classification.gpf.kdtknn.KDTreeKNNClassifierOp;
/**
* User interface for KDTree KNN
*/
public class KDTreeKNNClassifierOpUI extends KNNClassifierOpUI {
public KDTreeKNNClassifierOpUI() {
super(KDTreeKNNClassifierOp.CLASSIFIER_TYPE);
}
}
| 1,045 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AttributeDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-classification-ui/src/main/java/org/esa/snap/classification/gpf/ui/AttributeDialog.java | /*
* Copyright (C) 2016 by Array Systems Computing Inc. http://www.array.ca
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.classification.gpf.ui;
import org.esa.snap.graphbuilder.rcp.utils.DialogUtils;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.ui.GridBagUtils;
import org.esa.snap.ui.ModalDialog;
import javax.swing.*;
import java.awt.*;
/**
Attribute selection
*/
public class AttributeDialog extends ModalDialog {
private final JList<String> listControl;
private boolean ok = false;
public AttributeDialog(final String title, final String[] listData, final String defaultValue) {
super(SnapApp.getDefault().getMainFrame(), title, ModalDialog.ID_OK, null);
listControl = new JList<>(listData);
if(defaultValue != null) {
listControl.setSelectedValue(defaultValue, true);
}
final JPanel content = GridBagUtils.createPanel();
final GridBagConstraints gbc = DialogUtils.createGridBagConstraints();
gbc.insets.top = 2;
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(listControl);
content.add(scrollPane, gbc);
getJDialog().setMinimumSize(new Dimension(400, 100));
setContent(content);
}
public String getValue() {
return listControl.getSelectedValue();
}
protected void onOK() {
ok = true;
hide();
}
public boolean IsOK() {
return ok;
}
}
| 2,089 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MinimumDistanceClassifierOpUI.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-classification-ui/src/main/java/org/esa/snap/classification/gpf/ui/MinimumDistanceClassifierOpUI.java | /*
* Copyright (C) 2016 by Array Systems Computing Inc. http://www.array.ca
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.classification.gpf.ui;
import org.esa.snap.classification.gpf.minimumdistance.MinimumDistanceClassifierOp;
/**
* User interface for MinimumDistance
*/
public class MinimumDistanceClassifierOpUI extends BaseClassifierOpUI {
public MinimumDistanceClassifierOpUI() {
super(MinimumDistanceClassifierOp.CLASSIFIER_TYPE);
}
@Override
protected void setEnabled(final boolean enabled) {}
}
| 1,155 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RandomForestClassifierOpUI.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-classification-ui/src/main/java/org/esa/snap/classification/gpf/ui/RandomForestClassifierOpUI.java | /*
* Copyright (C) 2016 by Array Systems Computing Inc. http://www.array.ca
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.classification.gpf.ui;
import org.esa.snap.classification.gpf.randomForest.RandomForestClassifierOp;
import org.esa.snap.graphbuilder.rcp.utils.DialogUtils;
import javax.swing.*;
/**
* User interface for RandomForestClassifierTrainingOp
*/
public class RandomForestClassifierOpUI extends BaseClassifierOpUI {
private final JTextField treeCount = new JTextField("");
public RandomForestClassifierOpUI() {
super(RandomForestClassifierOp.CLASSIFIER_TYPE);
}
@Override
public void initParameters() {
super.initParameters();
treeCount.setText(String.valueOf(paramMap.get("treeCount")));
}
@Override
public void updateParameters() {
super.updateParameters();
paramMap.put("treeCount", Integer.parseInt(treeCount.getText()));
}
@Override
protected JPanel createPanel() {
final JPanel contentPane = super.createPanel();
classifiergbc.gridy++;
classifiergbc.weightx = 1;
DialogUtils.addComponent(classifierPanel, classifiergbc, "Number of trees:", treeCount);
return contentPane;
}
@Override
protected void setEnabled(final boolean enabled) {
treeCount.setEnabled(enabled);
}
}
| 1,976 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
KNNClassifierOpUI.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-classification-ui/src/main/java/org/esa/snap/classification/gpf/ui/KNNClassifierOpUI.java | /*
* Copyright (C) 2016 by Array Systems Computing Inc. http://www.array.ca
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.classification.gpf.ui;
import org.esa.snap.classification.gpf.knn.KNNClassifierOp;
import org.esa.snap.graphbuilder.rcp.utils.DialogUtils;
import javax.swing.*;
/**
* User interface for KNN
*/
public class KNNClassifierOpUI extends BaseClassifierOpUI {
private final JTextField numNeighbours = new JTextField("");
public KNNClassifierOpUI() {
this(KNNClassifierOp.CLASSIFIER_TYPE);
}
public KNNClassifierOpUI(String type) {
super(type);
}
@Override
public void initParameters() {
super.initParameters();
numNeighbours.setText(String.valueOf(paramMap.get("numNeighbours")));
}
@Override
public void updateParameters() {
super.updateParameters();
paramMap.put("numNeighbours", Integer.parseInt(numNeighbours.getText()));
}
@Override
protected JPanel createPanel() {
final JPanel contentPane = super.createPanel();
classifiergbc.gridy++;
DialogUtils.addComponent(classifierPanel, classifiergbc, "Number of neighbours:", numNeighbours);
return contentPane;
}
@Override
protected void setEnabled(final boolean enabled) {
numNeighbours.setEnabled(enabled);
}
}
| 1,975 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MaximumLikelihoodClassifierOpUI.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-classification-ui/src/main/java/org/esa/snap/classification/gpf/ui/MaximumLikelihoodClassifierOpUI.java | /*
* Copyright (C) 2016 by Array Systems Computing Inc. http://www.array.ca
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.classification.gpf.ui;
import org.esa.snap.classification.gpf.maximumlikelihood.MaximumLikelihoodClassifierOp;
/**
* User interface for MaximumLikelihood
*/
public class MaximumLikelihoodClassifierOpUI extends BaseClassifierOpUI {
public MaximumLikelihoodClassifierOpUI() {
super(MaximumLikelihoodClassifierOp.CLASSIFIER_TYPE);
}
@Override
protected void setEnabled(final boolean enabled) {}
}
| 1,167 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
package-info.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-classification-ui/src/main/java/org/esa/snap/classification/docs/package-info.java | @HelpSetRegistration(helpSet = "help.hs", position = 5920)
package org.esa.snap.classification.docs;
import eu.esa.snap.netbeans.javahelp.api.HelpSetRegistration; | 163 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
StartModule.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-watermask-ui/src/main/java/org/esa/snap/processor/StartModule.java | package org.esa.snap.processor;
import org.esa.snap.engine_utilities.util.ResourceUtils;
import org.openide.modules.OnStart;
/**
* Handle OnStart for module
*/
public class StartModule {
@OnStart
public static class StartOp implements Runnable {
@Override
public void run() {
ResourceUtils.installGraphs(this.getClass(), "org/esa/snap/processor/graphs/");
}
}
}
| 416 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
package-info.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-watermask-ui/src/main/java/org/esa/snap/processor/watermask/docs/package-info.java | @HelpSetRegistration(helpSet = "help.hs", position = 4420)
package org.esa.snap.processor.watermask.docs;
import eu.esa.snap.netbeans.javahelp.api.HelpSetRegistration;
| 169 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
WatermaskAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-watermask-ui/src/main/java/org/esa/snap/processor/watermask/ui/WatermaskAction.java | package org.esa.snap.processor.watermask.ui;
import org.esa.snap.core.gpf.ui.DefaultSingleTargetProductDialog;
import org.esa.snap.rcp.actions.AbstractSnapAction;
import org.esa.snap.ui.AppContext;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle;
import java.awt.event.ActionEvent;
@ActionID(category = "Processing", id = "org.esa.snap.processor.watermask.ui.WatermaskAction" )
@ActionRegistration(displayName = "#CTL_WatermaskAction_Text")
@ActionReference(path = "Menu/Raster/Masks", position = 400)
@NbBundle.Messages({"CTL_WatermaskAction_Text=Fractional Land/Water Mask"})
public class WatermaskAction extends AbstractSnapAction {
private static final String OPERATOR_ALIAS = "LandWaterMask";
private static final String HELP_ID = "watermaskScientificTool";
public WatermaskAction() {
putValue(SHORT_DESCRIPTION, "Creating an accurate, fractional, shapefile-based land-water mask.");
}
@Override
public void actionPerformed(ActionEvent e) {
final AppContext appContext = getAppContext();
final DefaultSingleTargetProductDialog dialog = new DefaultSingleTargetProductDialog(OPERATOR_ALIAS, appContext,
"Fractional Land/Water Mask",
HELP_ID);
dialog.setTargetProductNameSuffix("_watermask");
dialog.getJDialog().pack();
dialog.show();
}
}
| 1,612 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
package-info.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-help/src/main/java/org/esa/snap/snap/help/docs/package-info.java | @HelpSetRegistration(helpSet = "help.hs", position = 1000)
package org.esa.snap.snap.help.docs;
import eu.esa.snap.netbeans.javahelp.api.HelpSetRegistration;
| 159 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
LandCoverModule.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-land-cover-ui/src/main/java/org/esa/snap/landcover/LandCoverModule.java | /*
* Copyright (C) 2015 by Array Systems Computing Inc. http://www.array.ca
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.landcover;
import com.bc.ceres.core.ProgressMonitor;
import org.esa.snap.core.util.ResourceInstaller;
import org.esa.snap.core.util.SystemUtils;
import org.openide.modules.OnStart;
import java.io.IOException;
import java.nio.file.Path;
/**
* Handle OnStart for module
*/
public class LandCoverModule {
@OnStart
public static class StartOp implements Runnable {
@Override
public void run() {
installColorPalettes(this.getClass(), "org/esa/snap/landcover/auxdata/color_palettes/");
}
}
public static void installColorPalettes(final Class callingClass, final String path) {
final Path moduleBasePath = ResourceInstaller.findModuleCodeBasePath(callingClass);
final Path auxdataDir = getColorPalettesDir();
Path sourcePath = moduleBasePath.resolve(path);
final ResourceInstaller resourceInstaller = new ResourceInstaller(sourcePath, auxdataDir);
try {
resourceInstaller.install(".*.cpd", ProgressMonitor.NULL);
} catch (IOException e) {
SystemUtils.LOG.severe("Unable to install colour palettes "+moduleBasePath+" to "+auxdataDir+" "+e.getMessage());
}
}
private static Path getColorPalettesDir() {
return SystemUtils.getAuxDataPath().resolve("color_palettes");
}
}
| 2,066 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AddLandCoverOpUI.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-land-cover-ui/src/main/java/org/esa/snap/landcover/gpf/ui/AddLandCoverOpUI.java | /*
* Copyright (C) 2015 by Array Systems Computing Inc. http://www.array.ca
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.landcover.gpf.ui;
import org.esa.snap.core.dataio.ProductIOPlugInManager;
import org.esa.snap.core.dataio.ProductReaderPlugIn;
import org.esa.snap.core.dataop.resamp.ResamplingFactory;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.core.util.io.SnapFileFilter;
import org.esa.snap.graphbuilder.gpf.ui.BaseOperatorUI;
import org.esa.snap.graphbuilder.gpf.ui.UIValidation;
import org.esa.snap.graphbuilder.rcp.utils.DialogUtils;
import org.esa.snap.landcover.dataio.LandCoverFactory;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.SnapFileChooser;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
/**
* User interface for AddLandCoverOp
*/
public class AddLandCoverOpUI extends BaseOperatorUI {
private final JList<String> landCoverNamesList = new JList<>();
private final JList<File> externalFileList = new JList();
private final JButton externalFileBrowseButton = new JButton("...");
private final JComboBox<String> resamplingMethodCombo = new JComboBox<>(ResamplingFactory.resamplingNames);
private static final String lastLandcoverPathKey = "snap.external.landcoverDir";
@Override
public JComponent CreateOpTab(String operatorName, Map<String, Object> parameterMap, AppContext appContext) {
initializeOperatorUI(operatorName, parameterMap);
final JComponent panel = createPanel();
String[] Names = LandCoverFactory.getNameList();
// sort the list
final java.util.List<String> sortedNames = Arrays.asList(Names);
java.util.Collections.sort(sortedNames);
Names = sortedNames.toArray(new String[sortedNames.size()]);
landCoverNamesList.setListData(Names);
initParameters();
externalFileBrowseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final File[] files = getSelectedFiles();
if(files != null) {
externalFileList.removeAll();
externalFileList.setListData(files);
externalFileList.setSelectionInterval(0, externalFileList.getModel().getSize()-1);
landCoverNamesList.clearSelection();
}
}
});
return new JScrollPane(panel);
}
private static File[] getSelectedFiles() {
final JFileChooser fileChooser = createFileChooserDialog(lastLandcoverPathKey);
int result = fileChooser.showOpenDialog(SnapApp.getDefault().getMainFrame());
if (fileChooser.getCurrentDirectory() != null) {
SnapApp.getDefault().getPreferences().put(lastLandcoverPathKey, fileChooser.getCurrentDirectory().getPath());
}
if (result == JFileChooser.APPROVE_OPTION) {
return fileChooser.getSelectedFiles();
}
return null;
}
private static JFileChooser createFileChooserDialog(final String preferencesKey) {
final JFileChooser chooser = new SnapFileChooser();
chooser.setAcceptAllFileFilterUsed(true);
chooser.setMultiSelectionEnabled(true);
final String lastDir = SnapApp.getDefault().getPreferences().get(preferencesKey, SystemUtils.getUserHomeDir().getPath());
chooser.setCurrentDirectory(new File(lastDir));
final Iterator<ProductReaderPlugIn> iterator = ProductIOPlugInManager.getInstance().getAllReaderPlugIns();
java.util.List<SnapFileFilter> sortedFileFilters = SnapFileFilter.getSortedFileFilters(iterator);
sortedFileFilters.forEach(chooser::addChoosableFileFilter);
chooser.setFileFilter(chooser.getAcceptAllFileFilter());
return chooser;
}
@Override
public void initParameters() {
final String[] selectedLandCoverNames = (String[]) paramMap.get("landCoverNames");
if (selectedLandCoverNames != null) {
int[] sel = getListIndices(selectedLandCoverNames, LandCoverFactory.getNameList());
landCoverNamesList.setSelectedIndices(sel);
int[] s = landCoverNamesList.getSelectedIndices();
}
resamplingMethodCombo.setSelectedItem(paramMap.get("resamplingMethod"));
final File[] files = (File[]) paramMap.get("externalFiles");
if (files != null) {
externalFileList.setListData(files);
} else {
// backward compatibility
final File file = (File) paramMap.get("externalFile");
if(file != null) {
externalFileList.setListData(new File[] {file});
}
}
if(externalFileList.getModel().getSize() > 0) {
externalFileList.setSelectionInterval(0, externalFileList.getModel().getSize() - 1);
}
}
private static int[] getListIndices(final String[] selectedList, final String[] fullList) {
int[] selectionIndices = new int[selectedList.length];
int j = 0;
for (String n : selectedList) {
for (int i = 0; i < fullList.length; ++i) {
if (fullList[i].equals(n)) {
selectionIndices[j++] = i;
break;
}
}
}
return selectionIndices;
}
private static String[] getListStrings(final int[] selectedList, final String[] fullList) {
final ArrayList<String> stringList = new ArrayList<>(selectedList.length);
for (int i : selectedList) {
stringList.add(fullList[i]);
}
return stringList.toArray(new String[stringList.size()]);
}
@Override
public UIValidation validateParameters() {
return new UIValidation(UIValidation.State.OK, "");
}
@Override
public void updateParameters() {
if (!hasSourceProducts()) return;
final String[] names = getListStrings(landCoverNamesList.getSelectedIndices(), LandCoverFactory.getNameList());
if (names.length > 0) {
paramMap.put("landCoverNames", names);
} else {
paramMap.put("landCoverNames", new String[] {});
}
paramMap.put("resamplingMethod", resamplingMethodCombo.getSelectedItem());
if (!externalFileList.getSelectedValuesList().isEmpty()) {
final File[] files = externalFileList.getSelectedValuesList().toArray(new File[externalFileList.getSelectedValuesList().size()]);
paramMap.put("externalFiles", files);
}
}
private JComponent createPanel() {
final JPanel contentPane = new JPanel(new GridBagLayout());
final GridBagConstraints gbc = DialogUtils.createGridBagConstraints();
gbc.gridy++;
DialogUtils.addComponent(contentPane, gbc, "Land Cover Model:", landCoverNamesList);
gbc.gridy++;
externalFileList.setFixedCellWidth(500);
DialogUtils.addInnerPanel(contentPane, gbc, new JLabel("External Files"), externalFileList, externalFileBrowseButton);
gbc.gridy++;
DialogUtils.addComponent(contentPane, gbc, "Resampling Method:", resamplingMethodCombo);
gbc.gridy++;
gbc.gridx = 1;
contentPane.add(new JLabel("Integer data types will use nearest neighbour"), gbc);
DialogUtils.fillPanel(contentPane, gbc);
return contentPane;
}
} | 8,211 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
LandCoverMaskOpUI.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-land-cover-ui/src/main/java/org/esa/snap/landcover/gpf/ui/LandCoverMaskOpUI.java | /*
* Copyright (C) 2015 by Array Systems Computing Inc. http://www.array.ca
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.landcover.gpf.ui;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.IndexCoding;
import org.esa.snap.core.util.StringUtils;
import org.esa.snap.engine_utilities.datamodel.Unit;
import org.esa.snap.graphbuilder.gpf.ui.BaseOperatorUI;
import org.esa.snap.graphbuilder.gpf.ui.OperatorUIUtils;
import org.esa.snap.graphbuilder.gpf.ui.UIValidation;
import org.esa.snap.graphbuilder.rcp.utils.DialogUtils;
import org.esa.snap.ui.AppContext;
import javax.swing.*;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* User interface for Land Cover Mask
*/
public class LandCoverMaskOpUI extends BaseOperatorUI {
private final JList<String> bandList = new JList<>();
private final JComboBox<String> landCoverBandCombo = new JComboBox<>();
private final JLabel validLandCoverClassesLabel = new JLabel("Valid land cover classes:");
private final JList<String> validLandCoverClassesList = new JList<>();
private final JScrollPane validLandCoverClassesScroll = new JScrollPane(validLandCoverClassesList);
private final JLabel validPixelExpressionLabel = new JLabel("Valid pixel expression:");
private final JTextArea validPixelExpressionText = new JTextArea();
private final JCheckBox includeOtherBandsCheckBox = new JCheckBox("Include all other bands");
private final Map<Integer, Integer> classMap = new HashMap<>();
private final Map<Integer, String> classNameMap = new HashMap<>();
@Override
public JComponent CreateOpTab(String operatorName, Map<String, Object> parameterMap, AppContext appContext) {
initializeOperatorUI(operatorName, parameterMap);
final JComponent panel = createPanel();
landCoverBandCombo.addItemListener(e -> {
validLandCoverClassesList.removeAll();
String[] classes = getLandCoverClasses((String) landCoverBandCombo.getSelectedItem());
if(classes.length > 0) {
validLandCoverClassesList.setListData(classes);
final int[] selClasses = (int[]) paramMap.get("validLandCoverClasses");
if (selClasses != null) {
validLandCoverClassesList.setSelectedIndices(getClassIndexes(selClasses));
}
showLandCoverClasses(true);
} else {
showLandCoverClasses(false);
}
});
initParameters();
return new JScrollPane(panel);
}
private void showLandCoverClasses(final boolean flag) {
validLandCoverClassesScroll.setVisible(flag);
validLandCoverClassesLabel.setVisible(flag);
validLandCoverClassesList.setVisible(flag);
validPixelExpressionLabel.setVisible(!flag);
validPixelExpressionText.setVisible(!flag);
}
@Override
public void initParameters() {
final String[] bandNames = getBandNames();
OperatorUIUtils.initParamList(bandList, bandNames, (Object[]) paramMap.get("sourceBands"));
landCoverBandCombo.removeAllItems();
final String[] landCoverBandNames = getLandCoverNames();
for (String bandName : landCoverBandNames) {
landCoverBandCombo.addItem(bandName);
}
final String landCoverBand = (String) paramMap.get("landCoverBand");
if (landCoverBand != null && StringUtils.contains(landCoverBandNames, landCoverBand)) {
landCoverBandCombo.setSelectedItem(landCoverBand);
}
final String validPixelExpression = (String) paramMap.get("validPixelExpression");
if (validPixelExpression != null && !validPixelExpression.isEmpty()) {
validPixelExpressionText.setText(validPixelExpression);
}
final Boolean includeOtherBands = (Boolean) paramMap.get("includeOtherBands");
if (includeOtherBands != null) {
includeOtherBandsCheckBox.setSelected(includeOtherBands);
}
}
private String[] getLandCoverNames() {
final List<String> namesList = new ArrayList<>();
try {
if (sourceProducts != null) {
for (Band b : sourceProducts[0].getBands()) {
if (b.getUnit() != null && b.getUnit().equals(Unit.CLASS)) {
namesList.add(b.getName());
}
}
}
} catch (Exception e) {
// return empty namesList
}
return namesList.toArray(new String[0]);
}
private String[] getLandCoverClasses(final String landCoverBandName) {
final List<String> classList = new ArrayList<>();
if (landCoverBandName != null) {
final Band srcBand = sourceProducts[0].getBand(landCoverBandName);
if (srcBand != null) {
final IndexCoding indexCoding = srcBand.getIndexCoding();
if (indexCoding != null) {
final String[] indexNames = indexCoding.getIndexNames();
int i = 0;
for (String indexName : indexNames) {
classList.add(indexName);
int classVal = indexCoding.getIndexValue(indexName);
classMap.put(i++, classVal);
classNameMap.put(classVal, indexName);
}
}
}
}
return classList.toArray(new String[0]);
}
private int[] getClassIndexes(final int[] selClasses) {
final List<Integer> indexList = new ArrayList<>(selClasses.length);
for (int i = 0; i < validLandCoverClassesList.getModel().getSize(); ++i) {
final String listName = validLandCoverClassesList.getModel().getElementAt(i);
for (int selClass : selClasses) {
final String selClassName = classNameMap.get(selClass);
if (listName.equals(selClassName)) {
indexList.add(i);
}
}
}
final int[] index = new int[indexList.size()];
int i = 0;
for (Integer val : indexList) {
index[i++] = val;
}
return index;
}
@Override
public UIValidation validateParameters() {
return new UIValidation(UIValidation.State.OK, "");
}
@Override
public void updateParameters() {
if (!hasSourceProducts()) return;
OperatorUIUtils.updateParamList(bandList, paramMap, OperatorUIUtils.SOURCE_BAND_NAMES);
paramMap.put("landCoverBand", landCoverBandCombo.getSelectedItem());
paramMap.put("validLandCoverClasses", getSelectedClasses());
paramMap.put("validPixelExpression", validPixelExpressionText.getText());
paramMap.put("includeOtherBands", includeOtherBandsCheckBox.isSelected());
}
private int[] getSelectedClasses() {
final int[] selIndex = validLandCoverClassesList.getSelectedIndices();
final int[] classList = new int[selIndex.length];
for (int i = 0; i < selIndex.length; ++i) {
classList[i] = classMap.get(selIndex[i]);
}
return classList;
}
private JComponent createPanel() {
final JPanel contentPane = new JPanel(new GridBagLayout());
final GridBagConstraints gbc = DialogUtils.createGridBagConstraints();
contentPane.add(new JLabel("Source Bands:"), gbc);
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 1;
contentPane.add(new JScrollPane(bandList), gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy++;
DialogUtils.addComponent(contentPane, gbc, "Land Cover Band:", landCoverBandCombo);
gbc.gridy++;
contentPane.add(validLandCoverClassesLabel, gbc);
gbc.gridx = 1;
contentPane.add(validLandCoverClassesScroll, gbc);
gbc.gridx = 0;
contentPane.add(validPixelExpressionLabel, gbc);
gbc.gridx = 1;
contentPane.add(validPixelExpressionText, gbc);
gbc.gridy++;
gbc.gridx = 1;
contentPane.add(includeOtherBandsCheckBox, gbc);
DialogUtils.fillPanel(contentPane, gbc);
showLandCoverClasses(true);
return contentPane;
}
} | 9,125 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AddLandCoverAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-land-cover-ui/src/main/java/org/esa/snap/landcover/rcp/AddLandCoverAction.java | /*
* Copyright (C) 2015 by Array Systems Computing Inc. http://www.array.ca
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.landcover.rcp;
import org.esa.snap.landcover.dataio.LandCoverFactory;
import org.esa.snap.landcover.gpf.AddLandCoverOp;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.PropertyContainer;
import com.bc.ceres.binding.PropertyDescriptor;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.binding.ValidationException;
import com.bc.ceres.binding.Validator;
import com.bc.ceres.binding.ValueSet;
import com.bc.ceres.swing.TableLayout;
import com.bc.ceres.swing.binding.BindingContext;
import com.bc.ceres.swing.binding.ComponentAdapter;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.core.dataop.resamp.ResamplingFactory;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.ui.ModalDialog;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.ContextAwareAction;
import org.openide.util.HelpCtx;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.openide.util.WeakListeners;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.List;
import static org.esa.snap.landcover.gpf.AddLandCoverOp.AddLandCover;
@ActionID(
category = "Tools",
id = "AddLandCoverAction"
)
@ActionRegistration(
displayName = "#CTL_AddLandCoverAction_MenuText",
popupText = "#CTL_AddLandCoverAction_MenuText"
)
@ActionReferences({
@ActionReference(
path = "Context/Product/Product",
position = 21
),
@ActionReference(
path = "Context/Product/RasterDataNode",
position = 251
),
})
@NbBundle.Messages({
"CTL_AddLandCoverAction_MenuText=Add Land Cover Band",
"CTL_AddLandCoverAction_ShortDescription=Create a new land cover band from a selected land cover model"
})
public class AddLandCoverAction extends AbstractAction implements ContextAwareAction, LookupListener, HelpCtx.Provider {
private static final String HELP_ID = "addLandCoverBand";
private final Lookup lkp;
private Product product;
public static final String DIALOG_TITLE = "Add Land Cover Band";
public AddLandCoverAction() {
this(Utilities.actionsGlobalContext());
}
public AddLandCoverAction(Lookup lkp) {
super(Bundle.CTL_AddLandCoverAction_MenuText());
this.lkp = lkp;
Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class);
lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext));
setEnableState();
putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_AddLandCoverAction_ShortDescription());
}
@Override
public Action createContextAwareInstance(Lookup actionContext) {
return new AddLandCoverAction(actionContext);
}
@Override
public void resultChanged(LookupEvent ev) {
setEnableState();
}
private void setEnableState() {
ProductNode productNode = lkp.lookup(ProductNode.class);
boolean state = false;
if (productNode != null) {
product = productNode.getProduct();
state = product.getSceneGeoCoding() != null;
}
setEnabled(state);
}
@Override
public HelpCtx getHelpCtx() {
return new HelpCtx(HELP_ID);
}
@Override
public void actionPerformed(final ActionEvent event) {
try {
final AddLandCoverOp.LandCoverParameters param = requestDialogData(product);
if (param == null) {
return;
}
AddLandCover(product, param);
} catch (Exception e) {
SnapApp.getDefault().handleError(e.getMessage(), e);
}
}
private AddLandCoverOp.LandCoverParameters requestDialogData(final Product product) {
String[] Names = LandCoverFactory.getNameList();
// sort the list
final List<String> sortedNames = Arrays.asList(Names);
java.util.Collections.sort(sortedNames);
Names = sortedNames.toArray(new String[sortedNames.size()]);
final AddLandCoverOp.LandCoverParameters dialogData = new AddLandCoverOp.LandCoverParameters(Names[0], ResamplingFactory.NEAREST_NEIGHBOUR_NAME);
final PropertySet propertySet = PropertyContainer.createObjectBacked(dialogData);
configureNameProperty(propertySet, "name", Names, Names[0]);
configureNameProperty(propertySet, "resamplingMethod", ResamplingFactory.resamplingNames,
ResamplingFactory.NEAREST_NEIGHBOUR_NAME);
configureBandNameProperty(propertySet, "bandName", product);
final BindingContext ctx = new BindingContext(propertySet);
final JList landCoverList = new JList();
landCoverList.setVisibleRowCount(10);
ctx.bind("name", new SingleSelectionListComponentAdapter(landCoverList, product));
final JTextField bandNameField = new JTextField();
bandNameField.setColumns(30);
ctx.bind("bandName", bandNameField);
final TableLayout tableLayout = new TableLayout(2);
tableLayout.setTableAnchor(TableLayout.Anchor.WEST);
tableLayout.setTableFill(TableLayout.Fill.HORIZONTAL);
tableLayout.setTablePadding(4, 4);
for (int i = 0; i < 8; i++) {
tableLayout.setCellColspan(i, 0, 2);
}
final JPanel parameterPanel = new JPanel(tableLayout);
/*row 0*/
parameterPanel.add(new JLabel("Land Cover Model:"));
parameterPanel.add(new JScrollPane(landCoverList));
/*row 1*/
parameterPanel.add(new JLabel("Resampling method:"));
final JComboBox resamplingCombo = new JComboBox(ResamplingFactory.resamplingNames);
parameterPanel.add(resamplingCombo);
ctx.bind("resamplingMethod", resamplingCombo);
parameterPanel.add(new JLabel("Integer data types will use nearest neighbour"));
parameterPanel.add(new JLabel("Land cover band name:"));
parameterPanel.add(bandNameField);
final ModalDialog dialog = new ModalDialog(SnapApp.getDefault().getMainFrame(), DIALOG_TITLE, ModalDialog.ID_OK_CANCEL, HELP_ID);
dialog.setContent(parameterPanel);
if (dialog.show() == ModalDialog.ID_OK) {
return dialogData;
}
return null;
}
private static void configureNameProperty(PropertySet propertySet, String propertyName, String[] names, String defaultValue) {
final PropertyDescriptor descriptor = propertySet.getProperty(propertyName).getDescriptor();
descriptor.setValueSet(new ValueSet(names));
descriptor.setDefaultValue(defaultValue);
descriptor.setNotNull(true);
descriptor.setNotEmpty(true);
}
private static void configureBandNameProperty(PropertySet propertySet, String propertyName, Product product) {
final Property property = propertySet.getProperty(propertyName);
final PropertyDescriptor descriptor = property.getDescriptor();
descriptor.setNotNull(true);
descriptor.setNotEmpty(true);
descriptor.setValidator(new BandNameValidator(product));
}
private static class SingleSelectionListComponentAdapter extends ComponentAdapter implements ListSelectionListener, PropertyChangeListener {
private final JList list;
private final Product product;
public SingleSelectionListComponentAdapter(final JList list, final Product product) {
this.list = list;
this.product = product;
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
@Override
public JComponent[] getComponents() {
return new JComponent[]{list};
}
@Override
public void bindComponents() {
updateListModel();
getPropertyDescriptor().addAttributeChangeListener(this);
list.addListSelectionListener(this);
}
@Override
public void unbindComponents() {
getPropertyDescriptor().removeAttributeChangeListener(this);
list.removeListSelectionListener(this);
}
@Override
public void adjustComponents() {
Object value = getBinding().getPropertyValue();
if (value != null) {
list.setSelectedValue(value, true);
} else {
list.clearSelection();
}
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getSource() == getPropertyDescriptor() && evt.getPropertyName().equals("valueSet")) {
updateListModel();
}
}
private PropertyDescriptor getPropertyDescriptor() {
return getBinding().getContext().getPropertySet().getDescriptor(getBinding().getPropertyName());
}
private void updateListModel() {
ValueSet valueSet = getPropertyDescriptor().getValueSet();
if (valueSet != null) {
list.setListData(valueSet.getItems());
adjustComponents();
}
}
@Override
public void valueChanged(ListSelectionEvent event) {
if (event.getValueIsAdjusting()) {
return;
}
if (getBinding().isAdjustingComponents()) {
return;
}
final Property property = getBinding().getContext().getPropertySet().getProperty(getBinding().getPropertyName());
Object selectedValue = list.getSelectedValue();
try {
property.setValue(selectedValue);
final Property bandNameProperty = getBinding().getContext().getPropertySet().getProperty("bandName");
bandNameProperty.setValueFromText(AddLandCoverOp.getValidBandName((String) selectedValue, product));
// Now model is in sync with UI
getBinding().clearProblem();
} catch (ValidationException e) {
getBinding().reportProblem(e);
}
}
}
private static class BandNameValidator implements Validator {
private final Product product;
public BandNameValidator(Product product) {
this.product = product;
}
@Override
public void validateValue(Property property, Object value) throws ValidationException {
final String bandName = value.toString().trim();
if (!ProductNode.isValidNodeName(bandName)) {
throw new ValidationException(MessageFormat.format("The band name ''{0}'' appears not to be valid.\n" +
"Please choose another one.",
bandName));
} else if (product.containsBand(bandName)) {
throw new ValidationException(MessageFormat.format("The selected product already contains a band named ''{0}''.\n" +
"Please choose another one.",
bandName));
}
}
}
}
| 12,258 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
package-info.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-land-cover-ui/src/main/java/org/esa/snap/landcover/docs/package-info.java | @HelpSetRegistration(helpSet = "help.hs", position = 5330)
package org.esa.snap.landcover.docs;
import eu.esa.snap.netbeans.javahelp.api.HelpSetRegistration; | 158 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
VFSOptionsController.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-virtual-file-system-preferences-ui/src/main/java/org/esa/snap/ui/vfs/preferences/VFSOptionsController.java | package org.esa.snap.ui.vfs.preferences;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.swing.binding.BindingContext;
import org.esa.snap.rcp.preferences.DefaultConfigController;
import org.esa.snap.rcp.preferences.Preference;
import org.esa.snap.vfs.preferences.model.VFSRemoteFileRepositoriesController;
import org.netbeans.spi.options.OptionsPanelController;
import org.openide.util.HelpCtx;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Path;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A controller for VFS Remote File Repositories.
* Used for provide a UI to the strategy with storing VFS connection data.
*
* @author Adrian Draghici
*/
@OptionsPanelController.SubRegistration(location = "GeneralPreferences",
displayName = "#Options_DisplayName_VFSOptions",
keywords = "#Options_Keywords_VFSOptions",
keywordsCategory = "Remote File Repositories",
id = "VFS",
position = 11)
@org.openide.util.NbBundle.Messages({
"Options_DisplayName_VFSOptions=Remote File Repositories",
"Options_Keywords_VFSOptions=repositories, remote, file"
})
public class VFSOptionsController extends DefaultConfigController {
/**
* The column index for remote file repository name in remote file repositories table.
*/
private static final int REPO_NAME_COLUMN = 0;
/**
* The column index for remote file repository property name in remote file repository properties table.
*/
private static final int REPO_PROP_NAME_COLUMN = 0;
/**
* The column index for remote file repository property value in remote file repository properties table.
*/
private static final int REPO_PROP_VALUE_COLUMN = 1;
private static final String LOAD_ERROR_MESSAGE = "Unable to load VFS Remote File Repositories Properties from SNAP configuration file.";
private static final String SAVE_ERROR_MESSAGE = "Unable to save VFS Remote File Repositories Properties to SNAP configuration file.";
private static Logger logger = Logger.getLogger(VFSOptionsController.class.getName());
private static ImageIcon addButtonIcon;
private static ImageIcon removeButtonIcon;
static {
try {
addButtonIcon = loadImageIcon("icons/list-add.png");
removeButtonIcon = loadImageIcon("icons/list-remove.png");
} catch (Exception ex) {
logger.log(Level.WARNING, "Unable to load image resource. Details: " + ex.getMessage());
}
}
private final JTextField remoteRepositoryNameField = new JTextField();
private final JTextField remoteRepositorySchemaField = new JTextField();
private final JTextField remoteRepositoryAddressField = new JTextField();
private VFSRemoteFileRepositoriesController vfsRemoteFileRepositoriesController;
private JPanel remoteRepositoriesConfigsPanel;
private String currentRemoteRepositoryName = "";
private String currentRemoteRepositorySchema = "";
private String currentRemoteRepositoryAddress = "";
private String currentValue = "";
private String[] remoteRepositoriesIdsList;
private String[] remoteRepositoriesPropertiesIdsList;
private final JTable remoteRepositoriesListTable = getRemoteRepositoriesListTable();
private final JTable remoteRepositoriesPropertiesListTable = getRemoteRepositoriesPropertiesListTable();
private VFSOptionsBean vfsOptionsBean = new VFSOptionsBean();
private boolean isInitialized = false;
private static ImageIcon loadImageIcon(String imagePath) {
URL imageURL = VFSOptionsController.class.getResource(imagePath);
return (imageURL == null) ? null : new ImageIcon(imageURL);
}
/**
* Create a {@link PropertySet} object instance that holds all parameters.
* Clients that want to maintain properties need to overwrite this method.
*
* @return An instance of {@link PropertySet}, holding all configuration parameters.
* @see #createPropertySet(Object)
*/
@Override
protected PropertySet createPropertySet() {
return createPropertySet(vfsOptionsBean);
}
/**
* Create a panel that allows the user to set the parameters in the given {@link BindingContext}. Clients that want to create their own panel representation on the given properties need to overwrite this method.
*
* @param context The {@link BindingContext} for the panel.
* @return A JPanel instance for the given {@link BindingContext}, never {@code null}.
*/
@Override
protected JPanel createPanel(BindingContext context) {
Path configFile = VFSRemoteFileRepositoriesController.getDefaultConfigFilePath();
JPanel remoteFileRepositoriesTabUI = getRemoteFileRepositoriesTabUI();
try {
vfsRemoteFileRepositoriesController = new VFSRemoteFileRepositoriesController(configFile);
loadRemoteRepositoriesOnTable();
isInitialized = true;
} catch (IOException ex) {
logger.log(Level.SEVERE, LOAD_ERROR_MESSAGE + " Details: " + ex.getMessage());
JOptionPane.showMessageDialog(remoteRepositoriesConfigsPanel, LOAD_ERROR_MESSAGE, "Error loading VFS Remote file repositories configurations", JOptionPane.ERROR_MESSAGE);
}
return remoteFileRepositoriesTabUI;
}
/**
* Updates the UI.
*/
@Override
public void update() {
if (isInitialized) {
Path configFile = VFSRemoteFileRepositoriesController.getDefaultConfigFilePath();
try {
vfsRemoteFileRepositoriesController = new VFSRemoteFileRepositoriesController(configFile);
loadRemoteRepositoriesOnTable();
} catch (IOException ex) {
logger.log(Level.SEVERE, LOAD_ERROR_MESSAGE + " Details: " + ex.getMessage());
JOptionPane.showMessageDialog(remoteRepositoriesConfigsPanel, LOAD_ERROR_MESSAGE, "Error loading VFS Remote file repositories configurations", JOptionPane.ERROR_MESSAGE);
}
}
}
/**
* Saves the changes.
*/
@Override
public void applyChanges() {
if (isChanged()) {
try {
vfsRemoteFileRepositoriesController.saveProperties();
SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(remoteRepositoriesConfigsPanel, "VFS Remote File Repositories Properties saved successfully. Please restart SNAP to take effect.", "Save VFS Remote file repositories configurations", JOptionPane.INFORMATION_MESSAGE));
} catch (Exception ex) {
logger.log(Level.WARNING, SAVE_ERROR_MESSAGE + " Details: " + ex.getMessage());
SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(remoteRepositoriesConfigsPanel, SAVE_ERROR_MESSAGE + "\nReason: " + ex.getMessage(), "Error saving VFS Remote file repositories configurations", JOptionPane.ERROR_MESSAGE));
}
}
}
/**
* Cancels the changes.
*/
@Override
public void cancel() {
try {
vfsRemoteFileRepositoriesController.loadProperties();
} catch (IOException ex) {
logger.log(Level.SEVERE, LOAD_ERROR_MESSAGE + " Details: " + ex.getMessage());
JOptionPane.showMessageDialog(remoteRepositoriesConfigsPanel, LOAD_ERROR_MESSAGE, "Error loading VFS Remote file repositories configurations", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Check whether options changes.
*
* @return {@code true} if options is changed
*/
@Override
public boolean isChanged() {
return vfsRemoteFileRepositoriesController.isChanged();
}
/**
* Gets the Help Context for this Options Controller
*
* @return The Help Context
*/
@Override
public HelpCtx getHelpCtx() {
return new HelpCtx("vfs_editor");
}
/**
* Runs the event associated with button for adding remote file repository.
*/
private void runAddRemoteRepositoryButtonActionEvent() {
String lastRepositoryName = ".";
if (remoteRepositoriesListTable.getRowCount() > 0) {
lastRepositoryName = (String) remoteRepositoriesListTable.getModel().getValueAt(remoteRepositoriesListTable.getRowCount() - 1, REPO_NAME_COLUMN);
}
if (!lastRepositoryName.isEmpty()) {
try {
vfsRemoteFileRepositoriesController.registerNewRemoteRepository();
loadRemoteRepositoriesOnTable();
remoteRepositoriesListTable.changeSelection(remoteRepositoriesListTable.getRowCount() - 1, 0, false, false);
} catch (IllegalArgumentException ex) {
logger.log(Level.FINE, "Unable to add remote file repository. Details: " + ex.getMessage());
JOptionPane.showMessageDialog(remoteRepositoriesConfigsPanel, "Failed to add new remote repository.\nreason: " + ex, "Add new remote file repository", JOptionPane.ERROR_MESSAGE);
}
}
}
/**
* Creates and gets the button for adding remote file repository.
*
* @return The button for adding remote file repository
*/
private JButton getAddRemoteRepositoryButton() {
JButton addRemoteRepositoryButton = new JButton(addButtonIcon);
addRemoteRepositoryButton.setPreferredSize(new Dimension(20, 20));
addRemoteRepositoryButton.addActionListener(e -> runAddRemoteRepositoryButtonActionEvent());
return addRemoteRepositoryButton;
}
/**
* Runs the event associated with button for removing remote file repository.
*/
private void runRemoveRemoteRepositoryButtonActionEvent() {
try {
if (remoteRepositoriesListTable.getSelectedRow() >= 0) {
String repositoryName = (String) remoteRepositoriesListTable.getModel().getValueAt(remoteRepositoriesListTable.getSelectedRow(), REPO_NAME_COLUMN);
if (JOptionPane.showConfirmDialog(remoteRepositoriesListTable, "Are you sure to delete the following repository?\n" + repositoryName, "Delete Repository Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
String remoteRepositoryId = remoteRepositoriesIdsList[remoteRepositoriesListTable.getSelectedRow()];
vfsRemoteFileRepositoriesController.removeRemoteRepository(remoteRepositoryId);
loadRemoteRepositoriesOnTable();
}
} else {
JOptionPane.showMessageDialog(remoteRepositoriesConfigsPanel, "Please select a repository from list.", "Delete Repository", JOptionPane.WARNING_MESSAGE);
}
} catch (IllegalArgumentException ex) {
logger.log(Level.SEVERE, "Unable to delete remote file repository. Details: " + ex.getMessage());
JOptionPane.showMessageDialog(remoteRepositoriesConfigsPanel, "Failed to delete remote repository.\nreason: " + ex, "Delete remote file repository", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Creates and gets the button for removing remote file repository.
*
* @return The button for removing remote file repository
*/
private JButton getRemoveRemoteRepositoryButton() {
JButton removeRemoteRepositoryButton = new JButton(removeButtonIcon);
removeRemoteRepositoryButton.setPreferredSize(new Dimension(20, 20));
removeRemoteRepositoryButton.addActionListener(e -> runRemoveRemoteRepositoryButtonActionEvent());
return removeRemoteRepositoryButton;
}
/**
* Runs the event associated with selecting a row from remote file repositories table.
*/
private void runRemoteRepositoriesListTableListSelectionEvent() {
int selectedRow = remoteRepositoriesListTable.getSelectedRow();
if (selectedRow >= 0) {
String remoteRepositoryId = remoteRepositoriesIdsList[selectedRow];
String remoteRepositoryName = vfsRemoteFileRepositoriesController.getRemoteRepositoryName(remoteRepositoryId).getValue();
currentRemoteRepositoryName = remoteRepositoryName;
String remoteRepositorySchema = vfsRemoteFileRepositoriesController.getRemoteRepositorySchema(remoteRepositoryId).getValue();
currentRemoteRepositorySchema = remoteRepositorySchema;
String remoteRepositoryAddress = vfsRemoteFileRepositoriesController.getRemoteRepositoryAddress(remoteRepositoryId).getValue();
currentRemoteRepositoryAddress = remoteRepositoryAddress;
remoteRepositoryNameField.setText(remoteRepositoryName == null ? "" : remoteRepositoryName);
remoteRepositorySchemaField.setText(remoteRepositorySchema == null ? "" : remoteRepositorySchema);
remoteRepositoryAddressField.setText(remoteRepositoryAddress == null ? "" : remoteRepositoryAddress);
loadRemoteRepositoryPropertiesOnTable(remoteRepositoryId);
remoteRepositoriesConfigsPanel.setVisible(true);
} else {
remoteRepositoriesConfigsPanel.setVisible(false);
}
}
/**
* Creates and gets the remote file repositories table.
*
* @return The remote file repositories table
*/
private JTable getRemoteRepositoriesListTable() {
JTable newRemoteRepositoriesListTable = new JTable();
DefaultTableModel remoteRepositoriesListTableModel = new DefaultTableModel(
new Object[][]{
},
new String[]{
"Name"
}
) {
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
};
newRemoteRepositoriesListTable.setModel(remoteRepositoriesListTableModel);
newRemoteRepositoriesListTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
newRemoteRepositoriesListTable.getSelectionModel().addListSelectionListener(event -> runRemoteRepositoriesListTableListSelectionEvent());
return newRemoteRepositoriesListTable;
}
/**
* Creates and gets the panel with add and remove buttons for remote file repositories table.
*
* @return The panel with add and remove buttons
*/
private JPanel getRemoteRepositoriesListActionsPanel() {
JPanel remoteRepositoriesListActionsPanel = new JPanel();
remoteRepositoriesListActionsPanel.setLayout(new BoxLayout(remoteRepositoriesListActionsPanel, BoxLayout.PAGE_AXIS));
remoteRepositoriesListActionsPanel.add(getAddRemoteRepositoryButton());
remoteRepositoriesListActionsPanel.add(getRemoveRemoteRepositoryButton());
remoteRepositoriesListActionsPanel.add(Box.createVerticalGlue());
return remoteRepositoriesListActionsPanel;
}
/**
* Creates and gets the panel with add and remove buttons panel and remote file repositories table.
*
* @return The panel with add and remove buttons panel and remote file repositories table
*/
private JPanel getRemoteRepositoriesListPanel() {
JScrollPane remoteRepositoriesListSP = new JScrollPane();
remoteRepositoriesListSP.setViewportView(remoteRepositoriesListTable);
JPanel remoteRepositoriesListPanel = new JPanel();
remoteRepositoriesListPanel.setBorder(BorderFactory.createTitledBorder("Remote File Repositories List"));
remoteRepositoriesListPanel.setLayout(new BoxLayout(remoteRepositoriesListPanel, BoxLayout.LINE_AXIS));
remoteRepositoriesListPanel.setAutoscrolls(false);
remoteRepositoriesListPanel.add(getRemoteRepositoriesListActionsPanel());
remoteRepositoriesListPanel.add(remoteRepositoriesListSP);
return remoteRepositoriesListPanel;
}
/**
* Runs the event associated with leaving the remote file repository name field.
*/
private void runRemoteRepositoryNameFieldFocusLostEvent() {
String newRepositoryName = remoteRepositoryNameField.getText();
if (remoteRepositoriesListTable.getSelectedRow() >= 0 && !newRepositoryName.contentEquals(currentRemoteRepositoryName)) {
try {
String remoteRepositoryId = remoteRepositoriesIdsList[remoteRepositoriesListTable.getSelectedRow()];
vfsRemoteFileRepositoriesController.setRemoteRepositoryName(remoteRepositoryId, newRepositoryName);
remoteRepositoriesListTable.getModel().setValueAt(remoteRepositoryNameField.getText(), remoteRepositoriesListTable.getSelectedRow(), REPO_NAME_COLUMN);
currentRemoteRepositoryName = newRepositoryName;
} catch (IllegalArgumentException ex) {
JOptionPane.showMessageDialog(remoteRepositoriesConfigsPanel, "Invalid VFS repository name! Please check if it meets following requirements:\n- It must be unique\n- It must be alphanumeric.\n- Underscores and hyphens are allowed.\n- Length is between 3 and 25 characters.", "Update name for remote file repository", JOptionPane.WARNING_MESSAGE);
remoteRepositoryNameField.setText(currentRemoteRepositoryName);
}
}
}
/**
* Runs the event associated with leaving the remote file repository schema field.
*/
private void runRemoteRepositorySchemaFieldFocusLostEvent() {
String newRepositorySchema = remoteRepositorySchemaField.getText();
if (remoteRepositoriesListTable.getSelectedRow() >= 0 && !newRepositorySchema.contentEquals(currentRemoteRepositorySchema)) {
try {
String remoteRepositoryId = remoteRepositoriesIdsList[remoteRepositoriesListTable.getSelectedRow()];
vfsRemoteFileRepositoriesController.setRemoteRepositorySchema(remoteRepositoryId, newRepositorySchema);
currentRemoteRepositorySchema = newRepositorySchema;
} catch (IllegalArgumentException ex) {
JOptionPane.showMessageDialog(remoteRepositoriesConfigsPanel, "Invalid VFS repository schema! Please check if it meets following requirements:\n- It must be unique\n- It must be alpha-numeric", "Update schema for remote file repository", JOptionPane.WARNING_MESSAGE);
remoteRepositorySchemaField.setText(currentRemoteRepositorySchema);
}
}
}
/**
* Runs the event associated with leaving the remote file repository address field.
*/
private void runRemoteRepositoryAddressFieldFocusLostEvent() {
String newRepositoryAddress = remoteRepositoryAddressField.getText();
if (remoteRepositoriesListTable.getSelectedRow() >= 0 && !newRepositoryAddress.contentEquals(currentRemoteRepositoryAddress)) {
try {
String remoteRepositoryId = remoteRepositoriesIdsList[remoteRepositoriesListTable.getSelectedRow()];
vfsRemoteFileRepositoriesController.setRemoteRepositoryAddress(remoteRepositoryId, newRepositoryAddress);
currentRemoteRepositoryAddress = newRepositoryAddress;
} catch (IllegalArgumentException ex) {
JOptionPane.showMessageDialog(remoteRepositoriesConfigsPanel, "Invalid VFS repository address! Please check if it meets following requirements:\n- It must contains URL specific characters", "Update address for remote file repository", JOptionPane.WARNING_MESSAGE);
remoteRepositoryAddressField.setText(currentRemoteRepositoryAddress);
}
}
}
/**
* Creates and gets the panel with fields for remote file repository name, schema and address.
*
* @return The panel with fields for remote file repository name, schema and address
*/
private JPanel getRemoteRepositoriesSettingsPanel() {
JPanel namePanel = new JPanel();
namePanel.setLayout(new BoxLayout(namePanel, BoxLayout.LINE_AXIS));
JLabel remoteRepositoryNameLabel = new JLabel("Name:", SwingConstants.LEFT);
remoteRepositoryNameLabel.setPreferredSize(new Dimension(80, 10));
remoteRepositoryNameField.setAutoscrolls(true);
remoteRepositoryNameField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent evt) {
runRemoteRepositoryNameFieldFocusLostEvent();
}
});
namePanel.add(remoteRepositoryNameLabel);
namePanel.add(remoteRepositoryNameField);
JPanel schemaPanel = new JPanel();
schemaPanel.setLayout(new BoxLayout(schemaPanel, BoxLayout.LINE_AXIS));
JLabel remoteRepositorySchemaLabel = new JLabel("Schema:", SwingConstants.LEFT);
remoteRepositorySchemaLabel.setPreferredSize(new Dimension(80, 10));
remoteRepositorySchemaField.setAutoscrolls(true);
remoteRepositorySchemaField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent evt) {
runRemoteRepositorySchemaFieldFocusLostEvent();
}
});
schemaPanel.add(remoteRepositorySchemaLabel);
schemaPanel.add(remoteRepositorySchemaField);
JPanel addressPanel = new JPanel();
addressPanel.setLayout(new BoxLayout(addressPanel, BoxLayout.LINE_AXIS));
JLabel remoteRepositoryAddressLabel = new JLabel("Address:", SwingConstants.LEFT);
remoteRepositoryAddressLabel.setPreferredSize(new Dimension(80, 10));
remoteRepositoryAddressField.setAutoscrolls(true);
remoteRepositoryAddressField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent evt) {
runRemoteRepositoryAddressFieldFocusLostEvent();
}
});
addressPanel.add(remoteRepositoryAddressLabel);
addressPanel.add(remoteRepositoryAddressField);
JPanel remoteRepositoriesSettingsPanel = new JPanel();
remoteRepositoriesSettingsPanel.setBorder(BorderFactory.createTitledBorder("Settings"));
remoteRepositoriesSettingsPanel.setLayout(new BoxLayout(remoteRepositoriesSettingsPanel, BoxLayout.PAGE_AXIS));
remoteRepositoriesSettingsPanel.setAutoscrolls(false);
remoteRepositoriesSettingsPanel.add(namePanel);
remoteRepositoriesSettingsPanel.add(Box.createVerticalStrut(5));
remoteRepositoriesSettingsPanel.add(schemaPanel);
remoteRepositoriesSettingsPanel.add(Box.createVerticalStrut(5));
remoteRepositoriesSettingsPanel.add(addressPanel);
remoteRepositoriesSettingsPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, 150));
return remoteRepositoriesSettingsPanel;
}
/**
* Runs the event associated with button for adding remote file repository property.
*/
private void runAddRemoteRepositoryPropertyButtonActionEvent() {
String lastRepositoryPropertyName = ".";
String lastRepositoryPropertyValue = ".";
if (remoteRepositoriesPropertiesListTable.getRowCount() > 0) {
lastRepositoryPropertyName = (String) remoteRepositoriesPropertiesListTable.getModel().getValueAt(remoteRepositoriesPropertiesListTable.getRowCount() - 1, REPO_PROP_NAME_COLUMN);
lastRepositoryPropertyValue = (String) remoteRepositoriesPropertiesListTable.getModel().getValueAt(remoteRepositoriesPropertiesListTable.getRowCount() - 1, REPO_PROP_VALUE_COLUMN);
}
if (!lastRepositoryPropertyName.isEmpty() && !lastRepositoryPropertyValue.isEmpty()) {
try {
String remoteRepositoryId = remoteRepositoriesIdsList[remoteRepositoriesListTable.getSelectedRow()];
vfsRemoteFileRepositoriesController.registerNewRemoteRepositoryProperty(remoteRepositoryId);
loadRemoteRepositoryPropertiesOnTable(remoteRepositoryId);
} catch (IllegalArgumentException ex) {
logger.log(Level.FINE, "Unable to add remote file repository property. Details: " + ex.getMessage());
JOptionPane.showMessageDialog(remoteRepositoriesConfigsPanel, "Failed to add new remote repository property.\nreason: " + ex, "Add new remote file repository property", JOptionPane.ERROR_MESSAGE);
}
}
}
/**
* Creates and gets the button for adding remote file repository property.
*
* @return The button for adding remote file repository property
*/
private JButton getAddRemoteRepositoryPropertyButton() {
JButton addRemoteRepositoryPropertyButton = new JButton(addButtonIcon);
addRemoteRepositoryPropertyButton.setPreferredSize(new Dimension(20, 20));
addRemoteRepositoryPropertyButton.addActionListener(e -> runAddRemoteRepositoryPropertyButtonActionEvent());
return addRemoteRepositoryPropertyButton;
}
/**
* Runs the event associated with button for removing remote file repository property.
*/
private void runRemoveRemoteRepositoryPropertyButtonActionEvent() {
try {
if (remoteRepositoriesPropertiesListTable.getSelectedRow() >= 0) {
String repositoryPropertyName = (String) remoteRepositoriesPropertiesListTable.getModel().getValueAt(remoteRepositoriesPropertiesListTable.getSelectedRow(), REPO_PROP_NAME_COLUMN);
if (JOptionPane.showConfirmDialog(remoteRepositoriesPropertiesListTable, "Are you sure to delete the following repository property?\n" + repositoryPropertyName, "Delete Repository Property Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
String remoteRepositoryId = remoteRepositoriesIdsList[remoteRepositoriesListTable.getSelectedRow()];
String remoteRepositoryPropertyId = remoteRepositoriesPropertiesIdsList[remoteRepositoriesPropertiesListTable.getSelectedRow()];
vfsRemoteFileRepositoriesController.removeRemoteRepositoryProperty(remoteRepositoryId, remoteRepositoryPropertyId);
loadRemoteRepositoryPropertiesOnTable(remoteRepositoryId);
}
} else {
JOptionPane.showMessageDialog(remoteRepositoriesPropertiesListTable, "Please select a repository property from list.", "Delete Repository Property", JOptionPane.WARNING_MESSAGE);
}
} catch (IllegalArgumentException ex) {
logger.log(Level.SEVERE, "Unable to delete remote file repository property. Details: " + ex.getMessage());
JOptionPane.showMessageDialog(remoteRepositoriesConfigsPanel, "Failed to delete remote repository property.\nreason: " + ex, "Delete remote file repository property", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Creates and gets the button for removing remote file repository property.
*
* @return The button for removing remote file repository property
*/
private JButton getRemoveRemoteRepositoryPropertyButton() {
JButton removeRemoteRepositoryPropertyButton = new JButton(removeButtonIcon);
removeRemoteRepositoryPropertyButton.setPreferredSize(new Dimension(20, 20));
removeRemoteRepositoryPropertyButton.addActionListener(e -> runRemoveRemoteRepositoryPropertyButtonActionEvent());
return removeRemoteRepositoryPropertyButton;
}
/**
* Runs the event associated with selecting a row from remote file repositories properties table.
*/
private void runRemoteRepositoriesPropertiesListTableListSelectionEvent() {
int selectedRow = remoteRepositoriesPropertiesListTable.getSelectedRow();
int selectedColumn = remoteRepositoriesPropertiesListTable.getSelectedColumn();
if (selectedRow >= 0 && selectedRow < remoteRepositoriesPropertiesListTable.getRowCount()) {
currentValue = (String) remoteRepositoriesPropertiesListTable.getValueAt(selectedRow, selectedColumn);
}
}
/**
* Runs the event associated with editing a cell from remote file repository properties table.
*/
private void runRemoteRepositoriesPropertiesListTableModelEvent() {
int selectedRow = remoteRepositoriesPropertiesListTable.getSelectedRow();
int selectedColumn = remoteRepositoriesPropertiesListTable.getSelectedColumn();
if (selectedRow >= 0 && selectedRow < remoteRepositoriesPropertiesListTable.getRowCount()) {
String remoteRepositoryId = remoteRepositoriesIdsList[remoteRepositoriesListTable.getSelectedRow()];
String remoteRepositoryPropertyId = remoteRepositoriesPropertiesIdsList[selectedRow];
String newValue = (String) remoteRepositoriesPropertiesListTable.getValueAt(selectedRow, selectedColumn);
switch (selectedColumn) {
case REPO_PROP_NAME_COLUMN:
if (!newValue.contentEquals(currentValue)) {
try {
vfsRemoteFileRepositoriesController.setRemoteRepositoryPropertyName(remoteRepositoryId, remoteRepositoryPropertyId, newValue);
currentValue = newValue;
loadRemoteRepositoryPropertiesOnTable(remoteRepositoryId);
} catch (IllegalArgumentException ex) {
JOptionPane.showMessageDialog(remoteRepositoriesPropertiesListTable, "Invalid VFS repository property name! Please check if it meets following requirements:\n- Property name must be unique\n- Property name must be alphanumeric.\n- Underscores and hyphens are allowed in property name.\n- Length of property name is between 3 and 25 characters.", "Update remote file repository property name", JOptionPane.WARNING_MESSAGE);
remoteRepositoriesPropertiesListTable.setValueAt(currentValue, selectedRow, selectedColumn);
}
}
break;
case REPO_PROP_VALUE_COLUMN:
if (!newValue.contentEquals(currentValue)) {
try {
vfsRemoteFileRepositoriesController.setRemoteRepositoryPropertyValue(remoteRepositoryId, remoteRepositoryPropertyId, newValue);
currentValue = newValue;
loadRemoteRepositoryPropertiesOnTable(remoteRepositoryId);
} catch (IllegalArgumentException ex) {
JOptionPane.showMessageDialog(remoteRepositoriesPropertiesListTable, "Invalid VFS repository property value! Please check if it meets following requirements:\n- Property value must be not null", "Update remote file repository property value", JOptionPane.WARNING_MESSAGE);
remoteRepositoriesPropertiesListTable.setValueAt(currentValue, selectedRow, selectedColumn);
}
}
break;
default:
break;
}
}
}
/**
* Creates and gets the remote file repository properties table.
*
* @return The remote file repository properties table
*/
private JTable getRemoteRepositoriesPropertiesListTable() {
JTable newRemoteRepositoriesPropertiesListTable = new JTable();
DefaultTableModel remoteRepositoriesPropertiesListTableModel = new DefaultTableModel(
new Object[][]{
new Object[]{"", ""},
},
new String[]{
"Name", "Value"
}
) {
@Override
public boolean isCellEditable(int row, int column) {
return true;
}
};
newRemoteRepositoriesPropertiesListTable.setModel(remoteRepositoriesPropertiesListTableModel);
newRemoteRepositoriesPropertiesListTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
newRemoteRepositoriesPropertiesListTable.getModel().addTableModelListener(e -> runRemoteRepositoriesPropertiesListTableModelEvent());
newRemoteRepositoriesPropertiesListTable.getSelectionModel().addListSelectionListener(event -> runRemoteRepositoriesPropertiesListTableListSelectionEvent());
return newRemoteRepositoriesPropertiesListTable;
}
/**
* Creates and gets the panel with add and remove buttons for remote file repository properties table.
*
* @return The panel with add and remove buttons
*/
private JPanel getRemoteRepositoriesPropertiesListActionsPanel() {
JPanel remoteRepositoriesPropertiesActionsPanel = new JPanel();
remoteRepositoriesPropertiesActionsPanel.setLayout(new BoxLayout(remoteRepositoriesPropertiesActionsPanel, BoxLayout.PAGE_AXIS));
remoteRepositoriesPropertiesActionsPanel.add(getAddRemoteRepositoryPropertyButton());
remoteRepositoriesPropertiesActionsPanel.add(getRemoveRemoteRepositoryPropertyButton());
remoteRepositoriesPropertiesActionsPanel.add(Box.createVerticalGlue());
return remoteRepositoriesPropertiesActionsPanel;
}
/**
* Creates and gets the panel with add and remove buttons panel and remote file repository properties table.
*
* @return The panel with add and remove buttons panel and remote file repository properties table
*/
private JPanel getRemoteRepositoriesPropertiesListPanel() {
JScrollPane remoteRepositoriesPropertiesListSP = new JScrollPane();
remoteRepositoriesPropertiesListSP.setViewportView(remoteRepositoriesPropertiesListTable);
JPanel remoteRepositoriesPropertiesListPanel = new JPanel();
remoteRepositoriesPropertiesListPanel.setBorder(BorderFactory.createTitledBorder("Properties"));
remoteRepositoriesPropertiesListPanel.setLayout(new BoxLayout(remoteRepositoriesPropertiesListPanel, BoxLayout.LINE_AXIS));
remoteRepositoriesPropertiesListPanel.add(getRemoteRepositoriesPropertiesListActionsPanel());
remoteRepositoriesPropertiesListPanel.add(remoteRepositoriesPropertiesListSP);
return remoteRepositoriesPropertiesListPanel;
}
/**
* Creates and gets the panel with remote file repository configurations.
*
* @return The panel with remote file repository configurations
*/
private JPanel getRemoteRepositoriesConfigsPanel() {
remoteRepositoriesConfigsPanel = new JPanel();
remoteRepositoriesConfigsPanel.setBorder(BorderFactory.createTitledBorder("Remote File Repository Configurations"));
remoteRepositoriesConfigsPanel.setLayout(new BoxLayout(remoteRepositoriesConfigsPanel, BoxLayout.PAGE_AXIS));
remoteRepositoriesConfigsPanel.setAutoscrolls(false);
remoteRepositoriesConfigsPanel.add(getRemoteRepositoriesSettingsPanel());
remoteRepositoriesConfigsPanel.add(Box.createVerticalStrut(5));
remoteRepositoriesConfigsPanel.add(getRemoteRepositoriesPropertiesListPanel());
remoteRepositoriesConfigsPanel.setVisible(false);
return remoteRepositoriesConfigsPanel;
}
/**
* Creates and gets the panel with remote file repositories table and remote file repository configurations panel.
*
* @return The panel with remote file repositories table and remote file repository configurations panel
*/
private JSplitPane getRemoteFileRepositoriesPanel() {
JSplitPane remoteFileRepositoriesPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
remoteFileRepositoriesPanel.setOneTouchExpandable(false);
remoteFileRepositoriesPanel.setContinuousLayout(true);
remoteFileRepositoriesPanel.setDividerSize(5);
remoteFileRepositoriesPanel.setDividerLocation(0.5);
JPanel remoteRepositoriesListPane = getRemoteRepositoriesListPanel();
JPanel remoteRepositoriesConfigsPane = getRemoteRepositoriesConfigsPanel();
Dimension minimumSize = new Dimension(350, 410);
remoteRepositoriesListPane.setMinimumSize(minimumSize);
remoteRepositoriesConfigsPane.setMinimumSize(minimumSize);
remoteRepositoriesConfigsPane.addComponentListener(new ComponentListener() {
@Override
public void componentResized(ComponentEvent e) {
//nothing
}
@Override
public void componentMoved(ComponentEvent e) {
//nothing
}
@Override
public void componentShown(ComponentEvent e) {
remoteFileRepositoriesPanel.setDividerLocation(0.5);
}
@Override
public void componentHidden(ComponentEvent e) {
//nothing
}
});
remoteFileRepositoriesPanel.setLeftComponent(remoteRepositoriesListPane);
remoteFileRepositoriesPanel.setRightComponent(remoteRepositoriesConfigsPane);
return remoteFileRepositoriesPanel;
}
/**
* Creates and gets the root panel for remote file repositories tab ui.
*
* @return The root panel for remote file repositories tab ui
*/
private JPanel getRemoteFileRepositoriesTabUI() {
JPanel remoteFileRepositoriesTabUI = new JPanel(new BorderLayout());
remoteFileRepositoriesTabUI.add(getRemoteFileRepositoriesPanel());
remoteFileRepositoriesTabUI.setPreferredSize(new Dimension(730, 410));
return remoteFileRepositoriesTabUI;
}
/**
* Loads the remote file repositories names on remote file repositories table
*/
private void loadRemoteRepositoriesOnTable() {
((DefaultTableModel) remoteRepositoriesListTable.getModel()).setRowCount(0);
remoteRepositoriesListTable.clearSelection();
vfsOptionsBean.remoteRepositoriesIds = vfsRemoteFileRepositoriesController.getRemoteRepositoriesIds().getValue();
if (vfsOptionsBean.remoteRepositoriesIds != null && !vfsOptionsBean.remoteRepositoriesIds.isEmpty()) {
remoteRepositoriesIdsList = vfsOptionsBean.remoteRepositoriesIds.split(VFSRemoteFileRepositoriesController.LIST_ITEM_SEPARATOR);
for (String remoteRepositoryId : remoteRepositoriesIdsList) {
String remoteRepositoryName = vfsRemoteFileRepositoriesController.getRemoteRepositoryName(remoteRepositoryId).getValue();
((DefaultTableModel) remoteRepositoriesListTable.getModel()).addRow(new Object[]{remoteRepositoryName,});
}
}
}
/**
* Loads the remote file repository properties names and values on remote file repository properties table
*
* @param remoteRepositoryId The remote file repository id
*/
private void loadRemoteRepositoryPropertiesOnTable(String remoteRepositoryId) {
((DefaultTableModel) remoteRepositoriesPropertiesListTable.getModel()).setRowCount(0);
remoteRepositoriesPropertiesListTable.clearSelection();
String remoteRepositoryPropertiesIds = vfsRemoteFileRepositoriesController.getRemoteRepositoryPropertiesIds(remoteRepositoryId).getValue();
if (remoteRepositoryPropertiesIds != null && !remoteRepositoryPropertiesIds.isEmpty()) {
remoteRepositoriesPropertiesIdsList = remoteRepositoryPropertiesIds.split(VFSRemoteFileRepositoriesController.LIST_ITEM_SEPARATOR);
for (String remoteRepositoryPropertyId : remoteRepositoriesPropertiesIdsList) {
String remoteRepositoryPropertyName = vfsRemoteFileRepositoriesController.getRemoteRepositoryPropertyName(remoteRepositoryId, remoteRepositoryPropertyId).getValue();
String remoteRepositoryPropertyValue = vfsRemoteFileRepositoriesController.getRemoteRepositoryPropertyValue(remoteRepositoryId, remoteRepositoryPropertyId).getValue();
((DefaultTableModel) remoteRepositoriesPropertiesListTable.getModel()).addRow(new Object[]{remoteRepositoryPropertyName, remoteRepositoryPropertyName.matches(VFSRemoteFileRepositoriesController.CREDENTIAL_PROPERTY_NAME_REGEX) ? remoteRepositoryPropertyValue.replaceAll("(?s).", "*") : remoteRepositoryPropertyValue});
}
}
}
/**
* The bean with fields annoted with {@link Preference} for VFS Options.
*/
static class VFSOptionsBean {
@Preference(label = "Remote File Repositories List", key = VFSRemoteFileRepositoriesController.PREFERENCE_KEY_VFS_REPOSITORIES)
String remoteRepositoriesIds;
}
}
| 40,659 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.