[#45] Add the ability to create a client via wallet and password
All checks were successful
DCO / DCO (pull_request) Successful in 27s
Verify code phase / Verify code (pull_request) Successful in 1m38s

Signed-off-by: Ori Bruk <o.bruk@yadro.com>
This commit is contained in:
Ori Bruk 2025-03-04 17:01:51 +03:00
parent fe7d2968b8
commit db74919401
24 changed files with 141 additions and 558 deletions

View file

@ -1,5 +1,10 @@
# Changelog
## [0.8.0] - 2025-03-04
### Added
- Creating client via wallet and password
## [0.7.0] - 2025-02-20
### Added

View file

@ -25,7 +25,6 @@ import info.frostfs.sdk.FrostFSClient;
import info.frostfs.sdk.dto.container.Container;
import info.frostfs.sdk.dto.netmap.PlacementPolicy;
import info.frostfs.sdk.dto.netmap.Replica;
import info.frostfs.sdk.enums.BasicAcl;
import info.frostfs.sdk.jdo.ClientSettings;
import info.frostfs.sdk.jdo.parameters.CallContext;
import info.frostfs.sdk.jdo.parameters.container.PrmContainerCreate;
@ -41,7 +40,7 @@ public class ContainerExample {
FrostFSClient frostFSClient = new FrostFSClient(clientSettings);
// Create container
var placementPolicy = new PlacementPolicy(new Replica[]{new Replica(1)}, true, 0);
var placementPolicy = new PlacementPolicy(new Replica[]{new Replica(3)}, true, 1);
var prmContainerCreate = new PrmContainerCreate(new Container(placementPolicy));
var containerId = frostFSClient.createContainer(prmContainerCreate, callContext);

View file

@ -13,6 +13,7 @@ import info.frostfs.sdk.dto.session.SessionToken;
import info.frostfs.sdk.exceptions.ProcessFrostFSException;
import info.frostfs.sdk.jdo.ClientEnvironment;
import info.frostfs.sdk.jdo.ClientSettings;
import info.frostfs.sdk.jdo.ECDsa;
import info.frostfs.sdk.jdo.NetworkSettings;
import info.frostfs.sdk.jdo.parameters.CallContext;
import info.frostfs.sdk.jdo.parameters.ape.PrmApeChainAdd;
@ -40,6 +41,7 @@ import info.frostfs.sdk.utils.Validator;
import io.grpc.Channel;
import io.grpc.ClientInterceptors;
import io.grpc.ManagedChannel;
import org.apache.commons.lang3.StringUtils;
import java.util.List;
@ -66,10 +68,12 @@ public class FrostFSClient implements CommonClient {
? clientSettings.getChannel()
: initGrpcChannel(clientSettings);
var ecdsa = StringUtils.isBlank(clientSettings.getWif())
? new ECDsa(clientSettings.getWallet(), clientSettings.getPassword())
: new ECDsa(clientSettings.getWif());
Channel interceptChannel = ClientInterceptors.intercept(channel, MONITORING_CLIENT_INTERCEPTOR);
ClientEnvironment clientEnvironment = new ClientEnvironment(
clientSettings.getKey(), interceptChannel, new Version(), this,
new SessionCache(0)
ecdsa, interceptChannel, new Version(), this, new SessionCache(0)
);
Validator.validate(clientEnvironment);

View file

@ -0,0 +1,12 @@
package info.frostfs.sdk.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
public @interface ComplexAtLeastOneIsFilled {
AtLeastOneIsFilled[] value();
}

View file

@ -36,10 +36,10 @@ public class ClientEnvironment {
private SessionCache sessionCache;
public ClientEnvironment(String wif, Channel channel, Version version, FrostFSClient frostFSClient,
public ClientEnvironment(ECDsa key, Channel channel, Version version, FrostFSClient frostFSClient,
SessionCache sessionCache) {
this.key = new ECDsa(wif);
this.ownerId = new OwnerId(key.getPublicKeyByte());
this.key = key;
this.ownerId = new OwnerId(key.getAccount().getAddress());
this.version = version;
this.channel = channel;
this.frostFSClient = frostFSClient;
@ -47,16 +47,6 @@ public class ClientEnvironment {
this.address = channel.authority();
}
public ClientEnvironment(ECDsa key, Channel channel, Version version, FrostFSClient frostFSClient,
SessionCache sessionCache) {
this.key = key;
this.ownerId = new OwnerId(key.getPublicKeyByte());
this.version = version;
this.channel = channel;
this.frostFSClient = frostFSClient;
this.sessionCache = sessionCache;
}
public String getSessionKey() {
if (StringUtils.isBlank(sessionKey)) {
this.sessionKey = formCacheKey(address, getHexString(key.getPublicKeyByte()));

View file

@ -1,37 +1,61 @@
package info.frostfs.sdk.jdo;
import info.frostfs.sdk.annotations.AtLeastOneIsFilled;
import info.frostfs.sdk.annotations.NotNull;
import info.frostfs.sdk.annotations.ComplexAtLeastOneIsFilled;
import io.grpc.ChannelCredentials;
import io.grpc.ManagedChannel;
import lombok.Getter;
import lombok.experimental.FieldNameConstants;
import java.io.File;
@Getter
@FieldNameConstants
@AtLeastOneIsFilled(fields = {ClientSettings.Fields.host, ClientSettings.Fields.channel})
@ComplexAtLeastOneIsFilled(value = {
@AtLeastOneIsFilled(fields = {ClientSettings.Fields.host, ClientSettings.Fields.channel}),
@AtLeastOneIsFilled(fields = {ClientSettings.Fields.wif, ClientSettings.Fields.wallet}),
})
public class ClientSettings {
@NotNull
private final String key;
private String wif;
private File wallet;
private String password;
private String host;
private ChannelCredentials credentials;
private ManagedChannel channel;
public ClientSettings(String key, String host) {
this.key = key;
public ClientSettings(String wif, String host) {
this.wif = wif;
this.host = host;
}
public ClientSettings(String key, String host, ChannelCredentials credentials) {
this.key = key;
public ClientSettings(String wif, String host, ChannelCredentials credentials) {
this.wif = wif;
this.host = host;
this.credentials = credentials;
}
public ClientSettings(String key, ManagedChannel channel) {
this.key = key;
public ClientSettings(String wif, ManagedChannel channel) {
this.wif = wif;
this.channel = channel;
}
public ClientSettings(File wallet, String password, String host) {
this.wallet = wallet;
this.password = password;
this.host = host;
}
public ClientSettings(File wallet, String password, String host, ChannelCredentials credentials) {
this.wallet = wallet;
this.password = password;
this.host = host;
this.credentials = credentials;
}
public ClientSettings(File wallet, String password, ManagedChannel channel) {
this.wallet = wallet;
this.password = password;
this.channel = channel;
}
}

View file

@ -1,14 +1,25 @@
package info.frostfs.sdk.jdo;
import info.frostfs.sdk.annotations.NotNull;
import info.frostfs.sdk.exceptions.FrostFSException;
import info.frostfs.sdk.exceptions.ValidationFrostFSException;
import io.neow3j.wallet.Account;
import io.neow3j.wallet.nep6.NEP6Account;
import io.neow3j.wallet.nep6.NEP6Wallet;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.io.FileInputStream;
import java.security.PrivateKey;
import java.util.Optional;
import static info.frostfs.sdk.KeyExtension.*;
import static info.frostfs.sdk.KeyExtension.loadPrivateKey;
import static info.frostfs.sdk.constants.ErrorConst.WALLET_IS_INVALID;
import static info.frostfs.sdk.constants.ErrorConst.WIF_IS_INVALID;
import static info.frostfs.sdk.constants.FieldConst.EMPTY_STRING;
import static io.neow3j.wallet.Wallet.OBJECT_MAPPER;
import static java.util.Objects.isNull;
@Getter
public class ECDsa {
@ -22,13 +33,41 @@ public class ECDsa {
@NotNull
private final PrivateKey privateKey;
@NotNull
private final Account account;
public ECDsa(String wif) {
if (StringUtils.isEmpty(wif)) {
throw new ValidationFrostFSException(WIF_IS_INVALID);
}
this.privateKeyByte = getPrivateKeyFromWIF(wif);
this.publicKeyByte = loadPublicKey(privateKeyByte);
this.account = Account.fromWIF(wif);
this.privateKeyByte = account.getECKeyPair().getPrivateKey().getBytes();
this.publicKeyByte = account.getECKeyPair().getPublicKey().getEncoded(true);
this.privateKey = loadPrivateKey(privateKeyByte);
}
public ECDsa(File walletFile, String password) {
if (isNull(walletFile)) {
throw new ValidationFrostFSException(WALLET_IS_INVALID);
}
try (var walletStream = new FileInputStream(walletFile)) {
NEP6Wallet nep6Wallet = OBJECT_MAPPER.readValue(walletStream, NEP6Wallet.class);
Optional<NEP6Account> defaultAccount = nep6Wallet.getAccounts().stream()
.filter(NEP6Account::getDefault)
.findFirst();
var account = defaultAccount.map(Account::fromNEP6Account)
.orElseGet(() -> Account.fromNEP6Account(nep6Wallet.getAccounts().get(0)));
account.decryptPrivateKey(isNull(password) ? EMPTY_STRING : password);
this.account = account;
this.privateKeyByte = account.getECKeyPair().getPrivateKey().getBytes();
this.publicKeyByte = account.getECKeyPair().getPublicKey().getEncoded(true);
this.privateKey = loadPrivateKey(privateKeyByte);
} catch (Exception exp) {
throw new FrostFSException(exp.getMessage());
}
}
}

View file

@ -1,9 +1,6 @@
package info.frostfs.sdk.utils;
import info.frostfs.sdk.annotations.AtLeastOneIsFilled;
import info.frostfs.sdk.annotations.NotBlank;
import info.frostfs.sdk.annotations.NotNull;
import info.frostfs.sdk.annotations.Validate;
import info.frostfs.sdk.annotations.*;
import info.frostfs.sdk.constants.ErrorConst;
import info.frostfs.sdk.exceptions.ProcessFrostFSException;
import info.frostfs.sdk.exceptions.ValidationFrostFSException;
@ -37,6 +34,10 @@ public class Validator {
Class<?> clazz = object.getClass();
if (clazz.isAnnotationPresent(ComplexAtLeastOneIsFilled.class)) {
processComplexAtLeastOneIsFilled(object, clazz, errorMessage);
}
if (clazz.isAnnotationPresent(AtLeastOneIsFilled.class)) {
processAtLeastOneIsFilled(object, clazz, errorMessage);
}
@ -83,8 +84,22 @@ public class Validator {
process(getFieldValue(object, field), errorMessage);
}
private static <T> void processComplexAtLeastOneIsFilled(T object, Class<?> clazz, StringBuilder errorMessage) {
var annotation = clazz.getAnnotation(ComplexAtLeastOneIsFilled.class);
for (AtLeastOneIsFilled value : annotation.value()) {
processAtLeastOneIsFilled(object, clazz, errorMessage, value);
}
}
private static <T> void processAtLeastOneIsFilled(T object, Class<?> clazz, StringBuilder errorMessage) {
var annotation = clazz.getAnnotation(AtLeastOneIsFilled.class);
processAtLeastOneIsFilled(object, clazz, errorMessage, annotation);
}
private static <T> void processAtLeastOneIsFilled(T object,
Class<?> clazz,
StringBuilder errorMessage,
AtLeastOneIsFilled annotation) {
var emptyFieldsCount = 0;
for (String fieldName : annotation.fields()) {
var field = getField(clazz, fieldName);
@ -106,6 +121,7 @@ public class Validator {
}
}
private static <T> Object getFieldValue(T object, Field field) {
try {
return field.get(object);

View file

@ -2,7 +2,6 @@ package info.frostfs.sdk.services;
import frostfs.accounting.AccountingServiceGrpc;
import frostfs.accounting.Service;
import info.frostfs.sdk.Base58;
import info.frostfs.sdk.dto.object.OwnerId;
import info.frostfs.sdk.jdo.ClientEnvironment;
import info.frostfs.sdk.jdo.parameters.CallContext;
@ -12,6 +11,7 @@ import info.frostfs.sdk.tools.RequestConstructor;
import info.frostfs.sdk.tools.RequestSigner;
import info.frostfs.sdk.tools.Verifier;
import io.grpc.Channel;
import io.neow3j.crypto.Base58;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

View file

@ -1,141 +0,0 @@
package info.frostfs.sdk;
import info.frostfs.sdk.exceptions.ProcessFrostFSException;
import info.frostfs.sdk.exceptions.ValidationFrostFSException;
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
import static info.frostfs.sdk.ArrayHelper.concat;
import static info.frostfs.sdk.Helper.getSha256;
import static info.frostfs.sdk.constants.ErrorConst.*;
import static java.util.Objects.isNull;
public class Base58 {
public static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray();
public static final int BASE58_SYMBOL_COUNT = 58;
public static final int BASE256_SYMBOL_COUNT = 256;
private static final int BYTE_DIVISION = 0xFF;
private static final char ENCODED_ZERO = ALPHABET[0];
private static final char BASE58_ASCII_MAX_VALUE = 128;
private static final int[] INDEXES = new int[BASE58_ASCII_MAX_VALUE];
static {
Arrays.fill(INDEXES, -1);
for (int i = 0; i < ALPHABET.length; i++) {
INDEXES[ALPHABET[i]] = i;
}
}
private Base58() {
}
public static byte[] base58CheckDecode(String input) {
if (StringUtils.isEmpty(input)) {
throw new ValidationFrostFSException(INPUT_PARAM_IS_MISSING);
}
byte[] buffer = decode(input);
if (buffer.length < 4) {
throw new ProcessFrostFSException(String.format(DECODE_LENGTH_VALUE_TEMPLATE, buffer.length));
}
byte[] decode = Arrays.copyOfRange(buffer, 0, buffer.length - 4);
byte[] checksum = getSha256(getSha256(decode));
var bufferEnd = Arrays.copyOfRange(buffer, buffer.length - 4, buffer.length);
var checksumStart = Arrays.copyOfRange(checksum, 0, 4);
if (!Arrays.equals(bufferEnd, checksumStart)) {
throw new ProcessFrostFSException(INVALID_CHECKSUM);
}
return decode;
}
public static String base58CheckEncode(byte[] data) {
if (isNull(data)) {
throw new ValidationFrostFSException(INPUT_PARAM_IS_MISSING);
}
byte[] checksum = getSha256(getSha256(data));
var buffer = concat(data, Arrays.copyOfRange(checksum, 0, 4));
return encode(buffer);
}
public static String encode(byte[] input) {
if (input.length == 0) {
return "";
}
// Count leading zeros.
int zeros = 0;
while (zeros < input.length && input[zeros] == 0) {
++zeros;
}
// Convert base-256 digits to base-58 digits (plus conversion to ASCII characters)
input = Arrays.copyOf(input, input.length); // since we modify it in-place
char[] encoded = new char[input.length * 2]; // upper bound
int outputStart = encoded.length;
for (int inputStart = zeros; inputStart < input.length; ) {
encoded[--outputStart] = ALPHABET[divmod(input, inputStart, BASE256_SYMBOL_COUNT, BASE58_SYMBOL_COUNT)];
if (input[inputStart] == 0) {
++inputStart; // optimization - skip leading zeros
}
}
// Preserve exactly as many leading encoded zeros in output as there were leading zeros in input.
while (outputStart < encoded.length && encoded[outputStart] == ENCODED_ZERO) {
++outputStart;
}
while (--zeros >= 0) {
encoded[--outputStart] = ENCODED_ZERO;
}
// Return encoded string (including encoded leading zeros).
return new String(encoded, outputStart, encoded.length - outputStart);
}
public static byte[] decode(String input) {
if (input.isEmpty()) {
return new byte[0];
}
// Convert the base58-encoded ASCII chars to a base58 byte sequence (base58 digits).
byte[] input58 = new byte[input.length()];
for (int i = 0; i < input.length(); ++i) {
char c = input.charAt(i);
int digit = c < BASE58_ASCII_MAX_VALUE ? INDEXES[c] : -1;
if (digit < 0) {
throw new ValidationFrostFSException(String.format(INVALID_BASE58_CHARACTER_TEMPLATE, (int) c));
}
input58[i] = (byte) digit;
}
// Count leading zeros.
int zeros = 0;
while (zeros < input58.length && input58[zeros] == 0) {
++zeros;
}
// Convert base-58 digits to base-256 digits.
byte[] decoded = new byte[input.length()];
int outputStart = decoded.length;
for (int inputStart = zeros; inputStart < input58.length; ) {
decoded[--outputStart] = divmod(input58, inputStart, BASE58_SYMBOL_COUNT, BASE256_SYMBOL_COUNT);
if (input58[inputStart] == 0) {
++inputStart; // optimization - skip leading zeros
}
}
// Ignore extra leading zeroes that were added during the calculation.
while (outputStart < decoded.length && decoded[outputStart] == 0) {
++outputStart;
}
// Return decoded data (including original number of leading zeros).
return Arrays.copyOfRange(decoded, outputStart - zeros, decoded.length);
}
private static byte divmod(byte[] number, int firstDigit, int base, int divisor) {
// this is just long division which accounts for the base of the input digits
int remainder = 0;
for (int i = firstDigit; i < number.length; i++) {
int digit = (int) number[i] & BYTE_DIVISION;
int temp = remainder * base + digit;
number[i] = (byte) (temp / divisor);
remainder = temp % divisor;
}
return (byte) remainder;
}
}

View file

@ -4,7 +4,6 @@ import com.google.protobuf.ByteString;
import com.google.protobuf.Message;
import info.frostfs.sdk.exceptions.ValidationFrostFSException;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.crypto.digests.RIPEMD160Digest;
import java.math.BigInteger;
import java.security.MessageDigest;
@ -15,24 +14,11 @@ import static java.util.Objects.isNull;
public class Helper {
private static final String SHA256 = "SHA-256";
private static final int RIPEMD_160_HASH_BYTE_LENGTH = 20;
private static final int HEX_RADIX = 16;
private Helper() {
}
public static byte[] getRipemd160(byte[] value) {
if (isNull(value)) {
throw new ValidationFrostFSException(INPUT_PARAM_IS_MISSING);
}
var hash = new byte[RIPEMD_160_HASH_BYTE_LENGTH];
var digest = new RIPEMD160Digest();
digest.update(value, 0, value.length);
digest.doFinal(hash, 0);
return hash;
}
public static MessageDigest getSha256Instance() {
try {
return MessageDigest.getInstance(SHA256);

View file

@ -2,7 +2,6 @@ package info.frostfs.sdk;
import info.frostfs.sdk.exceptions.ProcessFrostFSException;
import info.frostfs.sdk.exceptions.ValidationFrostFSException;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.asn1.sec.SECNamedCurves;
import org.bouncycastle.asn1.sec.SECObjectIdentifiers;
import org.bouncycastle.asn1.x9.X9ECParameters;
@ -10,12 +9,7 @@ import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.jce.spec.ECNamedCurveSpec;
import org.bouncycastle.math.ec.ECPoint;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
@ -24,63 +18,20 @@ import java.security.spec.ECParameterSpec;
import java.security.spec.ECPrivateKeySpec;
import java.security.spec.ECPublicKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
import static info.frostfs.sdk.Helper.getRipemd160;
import static info.frostfs.sdk.Helper.getSha256;
import static info.frostfs.sdk.constants.ErrorConst.*;
import static info.frostfs.sdk.constants.ErrorConst.COMPRESSED_PUBLIC_KEY_WRONG_LENGTH_TEMPLATE;
import static info.frostfs.sdk.constants.ErrorConst.INPUT_PARAM_IS_MISSING;
import static java.util.Objects.isNull;
import static org.bouncycastle.util.BigIntegers.fromUnsignedByteArray;
public class KeyExtension {
public static final byte NEO_ADDRESS_VERSION = 0x35;
private static final String CURVE_NAME = "secp256r1";
private static final String SECURITY_ALGORITHM = "EC";
private static final int PS_IN_HASH160 = 0x0C;
private static final int DECODE_ADDRESS_LENGTH = 21;
private static final int COMPRESSED_PUBLIC_KEY_LENGTH = 33;
private static final int UNCOMPRESSED_PUBLIC_KEY_LENGTH = 65;
private static final int CHECK_SIG_DESCRIPTOR = ByteBuffer
.wrap(getSha256("System.Crypto.CheckSig".getBytes(StandardCharsets.US_ASCII)))
.order(ByteOrder.LITTLE_ENDIAN).getInt();
private KeyExtension() {
}
public static byte[] compress(byte[] publicKey) {
checkInputValue(publicKey);
if (publicKey.length != UNCOMPRESSED_PUBLIC_KEY_LENGTH) {
throw new ValidationFrostFSException(String.format(
UNCOMPRESSED_PUBLIC_KEY_WRONG_LENGTH_TEMPLATE, UNCOMPRESSED_PUBLIC_KEY_LENGTH, publicKey.length
));
}
var secp256R1 = SECNamedCurves.getByOID(SECObjectIdentifiers.secp256r1);
var point = secp256R1.getCurve().decodePoint(publicKey);
return point.getEncoded(true);
}
public static byte[] getPrivateKeyFromWIF(String wif) {
if (StringUtils.isEmpty(wif)) {
throw new ValidationFrostFSException(INPUT_PARAM_IS_MISSING);
}
var data = Base58.base58CheckDecode(wif);
return Arrays.copyOfRange(data, 1, data.length - 1);
}
public static byte[] loadPublicKey(byte[] privateKey) {
checkInputValue(privateKey);
X9ECParameters params = SECNamedCurves.getByOID(SECObjectIdentifiers.secp256r1);
ECDomainParameters domain = new ECDomainParameters(
params.getCurve(), params.getG(), params.getN(), params.getH()
);
ECPoint q = domain.getG().multiply(new BigInteger(1, privateKey));
ECPublicKeyParameters publicParams = new ECPublicKeyParameters(q, domain);
return publicParams.getQ().getEncoded(true);
}
public static PrivateKey loadPrivateKey(byte[] privateKey) {
checkInputValue(privateKey);
@ -134,58 +85,6 @@ public class KeyExtension {
}
}
public static byte[] getScriptHash(byte[] publicKey) {
checkInputValue(publicKey);
var script = createSignatureRedeemScript(publicKey);
return getRipemd160(getSha256(script));
}
public static String publicKeyToAddress(byte[] publicKey) {
checkInputValue(publicKey);
if (publicKey.length != COMPRESSED_PUBLIC_KEY_LENGTH) {
throw new ValidationFrostFSException(String.format(
ENCODED_COMPRESSED_PUBLIC_KEY_WRONG_LENGTH_TEMPLATE, COMPRESSED_PUBLIC_KEY_LENGTH, publicKey.length
));
}
return toAddress(getScriptHash(publicKey));
}
private static String toAddress(byte[] scriptHash) {
checkInputValue(scriptHash);
byte[] data = new byte[DECODE_ADDRESS_LENGTH];
data[0] = NEO_ADDRESS_VERSION;
System.arraycopy(scriptHash, 0, data, 1, scriptHash.length);
return Base58.base58CheckEncode(data);
}
private static byte[] getBytes(int value) {
byte[] buffer = new byte[4];
for (int i = 0; i < buffer.length; i++) {
buffer[i] = (byte) (value >> i * Byte.SIZE);
}
return buffer;
}
private static byte[] createSignatureRedeemScript(byte[] publicKey) {
checkInputValue(publicKey);
if (publicKey.length != COMPRESSED_PUBLIC_KEY_LENGTH) {
throw new ValidationFrostFSException(String.format(
ENCODED_COMPRESSED_PUBLIC_KEY_WRONG_LENGTH_TEMPLATE, COMPRESSED_PUBLIC_KEY_LENGTH, publicKey.length
));
}
var script = new byte[]{PS_IN_HASH160, COMPRESSED_PUBLIC_KEY_LENGTH}; //PUSHDATA1 33
script = ArrayHelper.concat(script, publicKey);
script = ArrayHelper.concat(script, new byte[]{UNCOMPRESSED_PUBLIC_KEY_LENGTH}); //SYSCALL
script = ArrayHelper.concat(script, getBytes(CHECK_SIG_DESCRIPTOR)); //Neo_Crypto_CheckSig
return script;
}
private static void checkInputValue(byte[] data) {
if (isNull(data) || data.length == 0) {
throw new ValidationFrostFSException(INPUT_PARAM_IS_MISSING);

View file

@ -1,56 +0,0 @@
package info.frostfs.sdk;
import info.frostfs.sdk.exceptions.ProcessFrostFSException;
import info.frostfs.sdk.exceptions.ValidationFrostFSException;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class Base58Test {
private static final String WIF = "L1YS4myg3xHPvi3FHeLaEt7G8upwJaWL5YLV7huviuUtXFpzBMqZ";
private static final byte[] DECODE = new byte[]{
-128, -128, -5, 30, -36, -118, 85, -67, -6, 81, 43, 93, -38, 106, 21, -88, 127, 15, 125, -79, -17, -40, 77,
-15, 122, -88, 72, 109, -47, 125, -80, -40, -38, 1
};
@Test
void base58DecodeEncode() {
//When + Then
assertEquals(WIF, Base58.base58CheckEncode(Base58.base58CheckDecode(WIF)));
}
@Test
void base58Decode_success() {
//When
var decode = Base58.base58CheckDecode(WIF);
//Then
assertThat(decode).hasSize(34).containsExactly(DECODE);
}
@Test
void base58Decode_wrong() {
//When + Then
assertThrows(ValidationFrostFSException.class, () -> Base58.base58CheckDecode(null));
assertThrows(ValidationFrostFSException.class, () -> Base58.base58CheckDecode(""));
assertThrows(ValidationFrostFSException.class, () -> Base58.base58CheckDecode("WIF"));
assertThrows(ProcessFrostFSException.class, () -> Base58.base58CheckDecode("fh"));
}
@Test
void base58Encode_success() {
//When
var encode = Base58.base58CheckEncode(DECODE);
//Then
assertEquals(WIF, encode);
}
@Test
void base58Encode_wrong() {
//When + Then
assertThrows(ValidationFrostFSException.class, () -> Base58.base58CheckEncode(null));
}
}

View file

@ -10,38 +10,6 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
public class HelperTest {
@Test
void getRipemd160_success() {
//Given
var value = new byte[]{1, 2, 3, 4, 5};
var expected = new byte[]
{-21, -126, 92, 75, 36, -12, 37, 7, 122, 6, 124, -61, -66, -12, 87, 120, 63, 90, -41, 5};
//When
var result = Helper.getRipemd160(value);
//Then
assertThat(result).hasSize(20).containsExactly(expected);
}
@Test
void getRipemd160_givenParamIsNull() {
//When + Then
assertThrows(ValidationFrostFSException.class, () -> Helper.getRipemd160(null));
}
@Test
void getRipemd160_givenParamsIsEmpty() {
//Given
var value = new byte[]{};
var expected = new byte[]
{-100, 17, -123, -91, -59, -23, -4, 84, 97, 40, 8, -105, 126, -24, -11, 72, -78, 37, -115, 49};
//When
var result = Helper.getRipemd160(value);
//Then
assertThat(result).hasSize(20).containsExactly(expected);
}
@Test
void getSha256Instance() {
//When

View file

@ -8,8 +8,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class KeyExtensionTest {
private static final String WIF = "L1YS4myg3xHPvi3FHeLaEt7G8upwJaWL5YLV7huviuUtXFpzBMqZ";
private static final String OWNER_ID = "NVxUSpEEJzYXZZtUs18PrJTD9QZkLLNQ8S";
private static final byte[] PRIVATE_KEY = new byte[]{
-128, -5, 30, -36, -118, 85, -67, -6, 81, 43, 93, -38, 106, 21, -88, 127, 15, 125, -79, -17, -40, 77, -15,
122, -88, 72, 109, -47, 125, -80, -40, -38
@ -24,38 +22,6 @@ public class KeyExtensionTest {
-68, -73, 65, -57, -26, 75, 4, -51, -40, -20, 75, 89, -59, 111, 96, -80, 56, 13
};
@Test
void getPrivateKeyFromWIF_success() {
//When
var privateKey = KeyExtension.getPrivateKeyFromWIF(WIF);
//Then
assertThat(privateKey).hasSize(32).containsExactly(PRIVATE_KEY);
}
@Test
void getPrivateKeyFromWIF_wrong() {
//When + Then
assertThrows(ValidationFrostFSException.class, () -> KeyExtension.getPrivateKeyFromWIF(""));
assertThrows(ValidationFrostFSException.class, () -> KeyExtension.getPrivateKeyFromWIF(null));
}
@Test
void loadPublicKey_success() {
//When
var publicKey = KeyExtension.loadPublicKey(PRIVATE_KEY);
//Then
assertThat(publicKey).hasSize(33).containsExactly(PUBLIC_KEY);
}
@Test
void loadPublicKey_wrong() {
//When + Then
assertThrows(ValidationFrostFSException.class, () -> KeyExtension.loadPublicKey(null));
assertThrows(ValidationFrostFSException.class, () -> KeyExtension.loadPublicKey(new byte[]{}));
}
@Test
void loadPrivateKey_success() {
//When
@ -92,61 +58,4 @@ public class KeyExtensionTest {
assertThrows(ValidationFrostFSException.class, () -> KeyExtension.getPublicKeyFromBytes(new byte[]{}));
assertThrows(ValidationFrostFSException.class, () -> KeyExtension.getPublicKeyFromBytes(PRIVATE_KEY));
}
@Test
void getScriptHash_success() {
//Given
var expected = new byte[]{
110, 42, -125, -76, -25, -44, -94, 22, -98, 117, -100, -5, 103, 74, -128, -51, 37, -116, -102, 71
};
//When
var hash = KeyExtension.getScriptHash(PUBLIC_KEY);
//Then
assertThat(hash).hasSize(20).containsExactly(expected);
}
@Test
void getScriptHash_wrong() {
//When + Then
assertThrows(ValidationFrostFSException.class, () -> KeyExtension.getScriptHash(null));
assertThrows(ValidationFrostFSException.class, () -> KeyExtension.getScriptHash(new byte[]{}));
assertThrows(ValidationFrostFSException.class, () -> KeyExtension.getScriptHash(PRIVATE_KEY));
}
@Test
void publicKeyToAddress_success() {
//When
var address = KeyExtension.publicKeyToAddress(PUBLIC_KEY);
//Then
assertEquals(OWNER_ID, address);
}
@Test
void publicKeyToAddress_wrong() {
//When + Then
assertThrows(ValidationFrostFSException.class, () -> KeyExtension.publicKeyToAddress(null));
assertThrows(ValidationFrostFSException.class, () -> KeyExtension.publicKeyToAddress(new byte[]{}));
assertThrows(ValidationFrostFSException.class, () -> KeyExtension.publicKeyToAddress(PRIVATE_KEY));
}
@Test
void compress_success() {
//When
var publicKey = KeyExtension.compress(UNCOMPRESSED_PUBLIC_KEY);
//Then
assertThat(publicKey).hasSize(33).containsExactly(PUBLIC_KEY);
}
@Test
void compress_wrong() {
//When + Then
assertThrows(ValidationFrostFSException.class, () -> KeyExtension.compress(null));
assertThrows(ValidationFrostFSException.class, () -> KeyExtension.compress(new byte[]{}));
assertThrows(ValidationFrostFSException.class, () -> KeyExtension.compress(PUBLIC_KEY));
}
}

View file

@ -20,6 +20,7 @@ public class ErrorConst {
public static final String UNEXPECTED_MESSAGE_TYPE_TEMPLATE = "unexpected message type, expected %s, actually %s";
public static final String WIF_IS_INVALID = "WIF is invalid";
public static final String WALLET_IS_INVALID = "wallet is not present";
public static final String UNEXPECTED_STREAM = "unexpected end of stream";
public static final String INVALID_HOST_TEMPLATE = "host %s has invalid format. Error: %s";
public static final String INVALID_RESPONSE = "invalid response";
@ -28,14 +29,7 @@ public class ErrorConst {
public static final String UNKNOWN_ENUM_VALUE_TEMPLATE = "unknown %s value: %s";
public static final String INPUT_PARAM_IS_NOT_SHA256 = "%s must be a sha256 hash";
public static final String DECODE_LENGTH_VALUE_TEMPLATE = "decode array length must be >= 4, but %s";
public static final String INVALID_BASE58_CHARACTER_TEMPLATE = "invalid character in Base58: 0x%04x";
public static final String INVALID_CHECKSUM = "checksum does not match";
public static final String WRONG_SIGNATURE_SIZE_TEMPLATE = "wrong signature size. Expected length=%s, actual=%s";
public static final String ENCODED_COMPRESSED_PUBLIC_KEY_WRONG_LENGTH_TEMPLATE =
"publicKey isn't encoded compressed public key. Expected length=%s, actual=%s";
public static final String UNCOMPRESSED_PUBLIC_KEY_WRONG_LENGTH_TEMPLATE =
"compress argument isn't uncompressed public key. Expected length=%s, actual=%s";
public static final String COMPRESSED_PUBLIC_KEY_WRONG_LENGTH_TEMPLATE =
"decompress argument isn't compressed public key. Expected length=%s, actual=%s";

View file

@ -1,8 +1,8 @@
package info.frostfs.sdk.dto.container;
import info.frostfs.sdk.Base58;
import info.frostfs.sdk.constants.AppConst;
import info.frostfs.sdk.exceptions.ValidationFrostFSException;
import io.neow3j.crypto.Base58;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;

View file

@ -1,8 +1,8 @@
package info.frostfs.sdk.dto.object;
import info.frostfs.sdk.Base58;
import info.frostfs.sdk.constants.AppConst;
import info.frostfs.sdk.exceptions.ValidationFrostFSException;
import io.neow3j.crypto.Base58;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;

View file

@ -1,14 +1,11 @@
package info.frostfs.sdk.dto.object;
import info.frostfs.sdk.Base58;
import info.frostfs.sdk.exceptions.ValidationFrostFSException;
import io.neow3j.crypto.Base58;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import static info.frostfs.sdk.KeyExtension.publicKeyToAddress;
import static info.frostfs.sdk.constants.ErrorConst.INPUT_PARAM_IS_MISSING;
import static info.frostfs.sdk.constants.ErrorConst.INPUT_PARAM_IS_MISSING_TEMPLATE;
import static java.util.Objects.isNull;
@Getter
public class OwnerId {
@ -24,14 +21,6 @@ public class OwnerId {
this.value = value;
}
public OwnerId(byte[] publicKey) {
if (isNull(publicKey) || publicKey.length == 0) {
throw new ValidationFrostFSException(INPUT_PARAM_IS_MISSING);
}
this.value = publicKeyToAddress(publicKey);
}
public byte[] toHash() {
return Base58.decode(value);
}

View file

@ -1,33 +0,0 @@
package info.frostfs.sdk.enums;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public enum BasicAcl {
PRIVATE(0x1C8C8CCC),
PUBLIC_RO(0x1FBF8CFF),
PUBLIC_RW(0x1FBFBFFF),
PUBLIC_APPEND(0x1FBF9FFF),
;
private static final Map<Integer, BasicAcl> ENUM_MAP_BY_VALUE;
static {
Map<Integer, BasicAcl> map = new HashMap<>();
for (BasicAcl basicAcl : BasicAcl.values()) {
map.put(basicAcl.value, basicAcl);
}
ENUM_MAP_BY_VALUE = Collections.unmodifiableMap(map);
}
public final int value;
BasicAcl(int value) {
this.value = value;
}
public static BasicAcl get(int value) {
return ENUM_MAP_BY_VALUE.get(value);
}
}

View file

@ -3,8 +3,6 @@ package info.frostfs.sdk.mappers.container;
import com.google.protobuf.ByteString;
import frostfs.container.Types;
import info.frostfs.sdk.dto.container.Container;
import info.frostfs.sdk.enums.BasicAcl;
import info.frostfs.sdk.exceptions.ProcessFrostFSException;
import info.frostfs.sdk.mappers.netmap.PlacementPolicyMapper;
import info.frostfs.sdk.mappers.netmap.VersionMapper;
import info.frostfs.sdk.mappers.object.OwnerIdMapper;
@ -14,7 +12,6 @@ import java.util.stream.Collectors;
import static info.frostfs.sdk.UuidExtension.asBytes;
import static info.frostfs.sdk.UuidExtension.asUuid;
import static info.frostfs.sdk.constants.ErrorConst.UNKNOWN_ENUM_VALUE_TEMPLATE;
import static java.util.Objects.isNull;
public class ContainerMapper {
@ -51,13 +48,6 @@ public class ContainerMapper {
return null;
}
var basicAcl = BasicAcl.get(containerGrpc.getBasicAcl());
if (isNull(basicAcl)) {
throw new ProcessFrostFSException(
String.format(UNKNOWN_ENUM_VALUE_TEMPLATE, BasicAcl.class.getName(), containerGrpc.getBasicAcl())
);
}
var attributes = containerGrpc.getAttributesList().stream()
.collect(Collectors.toMap(Types.Container.Attribute::getKey, Types.Container.Attribute::getValue));

View file

@ -2,8 +2,8 @@ package info.frostfs.sdk.mappers.object;
import com.google.protobuf.ByteString;
import frostfs.refs.Types;
import info.frostfs.sdk.Base58;
import info.frostfs.sdk.dto.object.OwnerId;
import io.neow3j.crypto.Base58;
import static java.util.Objects.isNull;

View file

@ -7,12 +7,8 @@ import info.frostfs.sdk.dto.netmap.PlacementPolicy;
import info.frostfs.sdk.dto.netmap.Replica;
import info.frostfs.sdk.dto.netmap.Version;
import info.frostfs.sdk.dto.object.OwnerId;
import info.frostfs.sdk.enums.BasicAcl;
import info.frostfs.sdk.exceptions.ProcessFrostFSException;
import info.frostfs.sdk.mappers.object.OwnerIdMapper;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import java.util.UUID;
@ -106,9 +102,8 @@ public class ContainerMapperTest {
assertNull(ContainerMapper.toGrpcMessage(null));
}
@ParameterizedTest
@EnumSource(value = BasicAcl.class)
void toModel_success(BasicAcl basicAcl) {
@Test
void toModel_success() {
//Given
var version = frostfs.refs.Types.Version.newBuilder()
.setMajor(1)
@ -137,7 +132,6 @@ public class ContainerMapperTest {
.build();
var container = Types.Container.newBuilder()
.setBasicAcl(basicAcl.value)
.setNonce(ByteString.copyFrom(asBytes(UUID.randomUUID())))
.setVersion(version)
.setPlacementPolicy(placementPolicy)
@ -178,15 +172,4 @@ public class ContainerMapperTest {
assertNull(ContainerMapper.toModel(null));
assertNull(ContainerMapper.toModel(Types.Container.getDefaultInstance()));
}
@Test
void toModel_notValid() {
//Given
var container = Types.Container.newBuilder()
.setBasicAcl(-1)
.build();
//When + Then
assertThrows(ProcessFrostFSException.class, () -> ContainerMapper.toModel(container));
}
}

View file

@ -17,7 +17,7 @@
</modules>
<properties>
<revision>0.7.0</revision>
<revision>0.8.0</revision>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
@ -28,6 +28,7 @@
<assertj.version>3.26.3</assertj.version>
<lombok.version>1.18.34</lombok.version>
<protobuf.version>3.23.0</protobuf.version>
<neow3j.version>3.23.0</neow3j.version>
</properties>
<dependencies>
@ -48,6 +49,11 @@
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>io.neow3j</groupId>
<artifactId>contract</artifactId>
<version>${neow3j.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>