Refactoring: apply Lombok, cleanup

This commit is contained in:
Manfred Karrer 2017-05-13 16:04:03 +02:00
parent 603c3c512e
commit 824e26eeca
44 changed files with 712 additions and 869 deletions

View file

@ -18,13 +18,8 @@
package io.bisq.common.crypto;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
@ -34,10 +29,5 @@ public class CryptoUtils {
final X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded());
return Base64.getEncoder().encodeToString(x509EncodedKeySpec.getEncoded());
}
public static PublicKey getPubKeyFromBytes(@NotNull byte[] publicKeyBytes)
throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
return KeyFactory.getInstance(Sig.KEY_ALGO, "BC").generatePublic(new X509EncodedKeySpec(publicKeyBytes));
}
}

View file

@ -39,14 +39,13 @@ import java.security.PublicKey;
public final class PubKeyRing implements NetworkPayload {
private final byte[] signaturePubKeyBytes;
private final byte[] encryptionPubKeyBytes;
private String pgpPubKeyAsPem;
transient private PublicKey signaturePubKey;
transient private PublicKey encryptionPubKey;
@Nullable
// TODO remove Nullable once impl.
transient private PGPPublicKey pgpPubKey;
private final String pgpPubKeyAsPem;
private PublicKey signaturePubKey;
private PublicKey encryptionPubKey;
@Nullable
private PGPPublicKey pgpPubKey;
public PubKeyRing(PublicKey signaturePubKey, PublicKey encryptionPubKey, @Nullable PGPPublicKey pgpPubKey) {
this.signaturePubKeyBytes = Sig.getSigPublicKeyBytes(signaturePubKey);

View file

@ -17,6 +17,7 @@
package io.bisq.common.locale;
import io.bisq.common.proto.ProtobufferException;
import io.bisq.common.proto.persistable.PersistablePayload;
import io.bisq.generated.protobuffer.PB;
import lombok.EqualsAndHashCode;
@ -47,6 +48,29 @@ public abstract class TradeCurrency implements PersistablePayload, Comparable<Tr
this.symbol = symbol;
}
///////////////////////////////////////////////////////////////////////////////////////////
// PROTO BUFFER
///////////////////////////////////////////////////////////////////////////////////////////
public static TradeCurrency fromProto(PB.TradeCurrency proto) {
switch (proto.getMessageCase()) {
case FIAT_CURRENCY:
return new FiatCurrency(proto.getCode());
case CRYPTO_CURRENCY:
return new CryptoCurrency(proto.getCode(),
proto.getName(),
proto.getSymbol(),
proto.getCryptoCurrency().getIsAsset());
default:
throw new ProtobufferException("Unknown message case: " + proto.getMessageCase());
}
}
///////////////////////////////////////////////////////////////////////////////////////////
// API
///////////////////////////////////////////////////////////////////////////////////////////
public String getDisplayPrefix() {
return "";
}
@ -64,16 +88,4 @@ public abstract class TradeCurrency implements PersistablePayload, Comparable<Tr
return this.code.compareTo(other.code);
}
public static TradeCurrency fromProto(PB.TradeCurrency tradeCurrency) {
switch (tradeCurrency.getMessageCase()) {
case FIAT_CURRENCY:
return new FiatCurrency(tradeCurrency.getCode());
case CRYPTO_CURRENCY:
return new CryptoCurrency(tradeCurrency.getCode(), tradeCurrency.getName(), tradeCurrency.getSymbol(),
tradeCurrency.getCryptoCurrency().getIsAsset());
default:
log.warn("Unknown tradecurrency: {}", tradeCurrency.getMessageCase());
return null;
}
}
}

View file

@ -30,8 +30,8 @@ public class ProtoCollectionUtil {
// Convenience
///////////////////////////////////////////////////////////////////////////////////////////
public static Iterable collectionToProto(Collection<? extends Payload> collection) {
return collection.stream().map(e -> e.toProtoMessage()).collect(Collectors.toList());
public static <T extends Message> Iterable<T> collectionToProto(Collection<? extends Payload> collection) {
return collection.stream().map(e -> (T) e.toProtoMessage()).collect(Collectors.toList());
}
public static <T> Iterable<T> collectionToProto(Collection<? extends Payload> collection, Function<? super Message, T> extra) {

View file

@ -20,11 +20,9 @@ package io.bisq.common.proto.persistable;
import com.google.protobuf.Message;
import lombok.Getter;
import lombok.Setter;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
@ -61,9 +59,6 @@ public class PersistableList<T extends PersistablePayload> implements Persistabl
@Override
public Message toProtoMessage() {
if (Objects.isNull(toProto)) {
throw new NotImplementedException();
}
return toProto.apply(list);
}

View file

@ -396,21 +396,22 @@ message Alert {
string version = 2;
bool is_update_info = 3;
string signature_as_base64 = 4;
bytes storage_public_key_bytes = 5;
map<string, string> extra_data_map = 6;
bytes owner_pub_key_bytes = 5;
map<string, string> extra_data = 6;
}
message Arbitrator {
NodeAddress node_address = 1;
repeated string language_codes = 2;
int64 registration_date = 3;
bytes registration_signature = 4;
string registration_signature = 4;
bytes registration_pub_key = 5;
PubKeyRing pub_key_ring = 6;
bytes btc_pub_key = 7;
string btc_address = 8;
string email_address = 9;
map<string, string> extra_data_map = 10;
string info = 10;
map<string, string> extra_data = 11;
}
message Mediator {
@ -422,7 +423,7 @@ message Mediator {
PubKeyRing pub_key_ring = 6;
string email_address = 7;
string info = 8;
map<string, string> extra_data_map = 9;
map<string, string> extra_data = 9;
}
message Filter {
@ -431,7 +432,7 @@ message Filter {
repeated PaymentAccountFilter banned_payment_accounts = 3;
string signature_as_base64 = 4;
bytes owner_pub_key_bytes = 5;
map<string, string> extra_data_map = 6;
map<string, string> extra_data = 6;
}
message PaymentAccountFilter {
@ -454,11 +455,11 @@ message CompensationRequestPayload {
int64 requested_btc = 11;
string btc_address = 12;
string node_address = 13;
bytes p2p_storage_signature_pub_key_bytes = 14;
string p2p_storage_signature_pub_key_as_hex = 15;
bytes owner_pub_key_bytes = 14;
string owner_pub_key_as_hex = 15;
string signature = 16;
string fee_tx_id = 17;
map<string, string> extra_data_map = 18;
map<string, string> extra_data = 18;
}
message TradeStatistics {
@ -470,14 +471,14 @@ message TradeStatistics {
int64 trade_date = 6;
string payment_method_id = 7;
int64 offer_date = 8;
bool use_market_based_price = 9;
double market_price_margin = 10;
bool offer_use_market_based_price = 9;
double offer_market_price_margin = 10;
int64 offer_amount = 11;
int64 offer_min_amount = 12;
string offer_id = 13;
string deposit_tx_id = 14;
PubKeyRing pub_key_ring = 15;
map<string, string> extra_data_map = 16;
map<string, string> extra_data = 16;
}
@ -485,7 +486,7 @@ message MailboxStoragePayload {
PrefixedSealedAndSignedMessage prefixed_sealed_and_signed_message = 1;
bytes sender_pub_key_for_add_operation_bytes = 2;
bytes owner_pub_key_bytes = 3;
map<string, string> extra_data_map = 4;
map<string, string> extra_data = 4;
}
message OfferPayload {
@ -512,7 +513,7 @@ message OfferPayload {
double market_price_margin = 16;
int64 amount = 17;
int64 min_amount = 18;
NodeAddress maker_node_address = 19;
NodeAddress owner_node_address = 19;
PubKeyRing pub_key_ring = 20;
string maker_payment_account_id = 21;
string offer_fee_payment_tx_id = 22;
@ -530,7 +531,7 @@ message OfferPayload {
int64 upper_close_price = 34;
bool is_private_offer = 35;
string hash_of_challenge = 36;
map<string, string> extra_data_map = 37;
map<string, string> extra_data = 37;
bool is_currency_for_maker_fee_btc = 38;
}

View file

@ -41,6 +41,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
@ToString
@Slf4j
public final class Alert implements StoragePayload {
private final long TTL = TimeUnit.DAYS.toMillis(30);
private final String message;
private final String version;
private final boolean isUpdateInfo;
@ -92,23 +93,23 @@ public final class Alert implements StoragePayload {
checkNotNull(ownerPubKeyBytes, "storagePublicKeyBytes must not be null");
checkNotNull(signatureAsBase64, "signatureAsBase64 must not be null");
final PB.Alert.Builder builder = PB.Alert.newBuilder()
.setMessage(getMessage())
.setIsUpdateInfo(isUpdateInfo())
.setVersion(getVersion())
.setMessage(message)
.setIsUpdateInfo(isUpdateInfo)
.setVersion(version)
.setOwnerPubKeyBytes(ByteString.copyFrom(ownerPubKeyBytes))
.setSignatureAsBase64(getSignatureAsBase64());
.setSignatureAsBase64(signatureAsBase64);
Optional.ofNullable(getExtraDataMap()).ifPresent(builder::putAllExtraData);
return PB.StoragePayload.newBuilder().setAlert(builder).build();
}
public static Alert fromProto(PB.Alert alert) {
return new Alert(alert.getMessage(),
alert.getIsUpdateInfo(),
alert.getVersion(),
alert.getOwnerPubKeyBytes().toByteArray(),
alert.getSignatureAsBase64(),
CollectionUtils.isEmpty(alert.getExtraDataMap()) ?
null : alert.getExtraDataMap());
public static Alert fromProto(PB.Alert proto) {
return new Alert(proto.getMessage(),
proto.getIsUpdateInfo(),
proto.getVersion(),
proto.getOwnerPubKeyBytes().toByteArray(),
proto.getSignatureAsBase64(),
CollectionUtils.isEmpty(proto.getExtraDataMap()) ?
null : proto.getExtraDataMap());
}
@ -119,15 +120,11 @@ public final class Alert implements StoragePayload {
public void setSigAndPubKey(String signatureAsBase64, PublicKey ownerPubKey) {
this.signatureAsBase64 = signatureAsBase64;
this.ownerPubKey = ownerPubKey;
ownerPubKeyBytes = Sig.getSigPublicKeyBytes(ownerPubKey);
}
public boolean isNewVersion() {
return Version.isNewVersion(version);
}
@Override
public long getTTL() {
return TimeUnit.DAYS.toMillis(30);
}
}

View file

@ -29,7 +29,6 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import javax.annotation.Nullable;
import java.nio.charset.Charset;
import java.security.PublicKey;
import java.util.Date;
import java.util.List;
@ -44,18 +43,18 @@ import java.util.stream.Collectors;
@Getter
public final class Arbitrator implements StoragePayload {
public static final long TTL = TimeUnit.DAYS.toMillis(10);
// Payload
private final byte[] btcPubKey;
private final PubKeyRing pubKeyRing;
private final NodeAddress nodeAddress;
private final List<String> languageCodes;
private final byte[] btcPubKey;
private final String btcAddress;
private final PubKeyRing pubKeyRing;
private final List<String> languageCodes;
private final long registrationDate;
private final String registrationSignature;
private final byte[] registrationPubKey;
private final String registrationSignature;
@Nullable
private final String emailAddress;
@Nullable
private final String info;
// Should be only used in emergency case if we need to add data but do not want to break backward compatibility
// at the P2P network storage checks. The hash of the object will be used to verify if the data is valid. Any new
@ -63,7 +62,6 @@ public final class Arbitrator implements StoragePayload {
@Nullable
private Map<String, String> extraDataMap;
// Called from domain and PB
public Arbitrator(NodeAddress nodeAddress,
byte[] btcPubKey,
String btcAddress,
@ -73,22 +71,54 @@ public final class Arbitrator implements StoragePayload {
byte[] registrationPubKey,
String registrationSignature,
@Nullable String emailAddress,
@Nullable String info,
@Nullable Map<String, String> extraDataMap) {
this.nodeAddress = nodeAddress;
this.btcPubKey = btcPubKey;
this.btcAddress = btcAddress;
this.pubKeyRing = pubKeyRing;
this.languageCodes = languageCodes;
this.emailAddress = emailAddress;
this.registrationDate = registrationDate.getTime();
this.registrationPubKey = registrationPubKey;
this.registrationSignature = registrationSignature;
this.emailAddress = emailAddress;
this.info = info;
this.extraDataMap = extraDataMap;
}
///////////////////////////////////////////////////////////////////////////////////////////
// PROTO BUFFER
///////////////////////////////////////////////////////////////////////////////////////////
@Override
public long getTTL() {
return TTL;
public PB.StoragePayload toProtoMessage() {
final PB.Arbitrator.Builder builder = PB.Arbitrator.newBuilder()
.setNodeAddress(nodeAddress.toProtoMessage())
.setBtcPubKey(ByteString.copyFrom(btcPubKey))
.setBtcAddress(btcAddress)
.setPubKeyRing(pubKeyRing.toProtoMessage())
.addAllLanguageCodes(languageCodes)
.setRegistrationDate(registrationDate)
.setRegistrationPubKey(ByteString.copyFrom(registrationPubKey))
.setRegistrationSignature(registrationSignature);
Optional.ofNullable(emailAddress).ifPresent(builder::setEmailAddress);
Optional.ofNullable(info).ifPresent(builder::setInfo);
Optional.ofNullable(extraDataMap).ifPresent(builder::putAllExtraData);
return PB.StoragePayload.newBuilder().setArbitrator(builder).build();
}
public static Arbitrator fromProto(PB.Arbitrator proto) {
return new Arbitrator(NodeAddress.fromProto(proto.getNodeAddress()),
proto.getBtcPubKey().toByteArray(),
proto.getBtcAddress(),
PubKeyRing.fromProto(proto.getPubKeyRing()),
proto.getLanguageCodesList().stream().collect(Collectors.toList()),
new Date(proto.getRegistrationDate()),
proto.getRegistrationPubKey().toByteArray(),
proto.getRegistrationSignature(),
proto.getEmailAddress().isEmpty() ? null : proto.getEmailAddress(),
proto.getInfo().isEmpty() ? null : proto.getInfo(),
CollectionUtils.isEmpty(proto.getExtraDataMap()) ? null : proto.getExtraDataMap());
}
@Override
@ -97,36 +127,7 @@ public final class Arbitrator implements StoragePayload {
}
@Override
public PB.StoragePayload toProtoMessage() {
final PB.Arbitrator.Builder builder = PB.Arbitrator.newBuilder()
.setBtcPubKey(ByteString.copyFrom(btcPubKey))
.setPubKeyRing(pubKeyRing.toProtoMessage())
.setNodeAddress(nodeAddress.toProtoMessage())
.addAllLanguageCodes(languageCodes)
.setBtcAddress(btcAddress)
.setRegistrationDate(registrationDate)
.setRegistrationSignature(ByteString.copyFrom(registrationSignature.getBytes())) // string does not conform to UTF-8 !
.setRegistrationPubKey(ByteString.copyFrom(registrationPubKey));
Optional.ofNullable(extraDataMap).ifPresent(builder::putAllExtraDataMap);
Optional.ofNullable(emailAddress).ifPresent(builder::setEmailAddress);
return PB.StoragePayload.newBuilder().setArbitrator(builder).build();
public long getTTL() {
return TTL;
}
public static Arbitrator fromProto(PB.Arbitrator arbitrator) {
List<String> strings = arbitrator.getLanguageCodesList().stream().collect(Collectors.toList());
Date date = new Date(arbitrator.getRegistrationDate());
String emailAddress = arbitrator.getEmailAddress().isEmpty() ? null : arbitrator.getEmailAddress();
return new Arbitrator(NodeAddress.fromProto(arbitrator.getNodeAddress()),
arbitrator.getBtcPubKey().toByteArray(),
arbitrator.getBtcAddress(),
PubKeyRing.fromProto(arbitrator.getPubKeyRing()),
strings,
date,
arbitrator.getRegistrationPubKey().toByteArray(),
arbitrator.getRegistrationSignature().toString(Charset.forName("UTF-8")), // convert back to String
emailAddress,
CollectionUtils.isEmpty(arbitrator.getExtraDataMapMap()) ?
null : arbitrator.getExtraDataMapMap());
}
}

View file

@ -30,7 +30,6 @@ import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.util.encoders.Hex;
@ -42,7 +41,6 @@ import java.util.stream.Collectors;
@Slf4j
@EqualsAndHashCode
@ToString
@Getter
public final class Dispute implements NetworkPayload {
private final String tradeId;
@ -50,7 +48,6 @@ public final class Dispute implements NetworkPayload {
private final int traderId;
private final boolean disputeOpenerIsBuyer;
private final boolean disputeOpenerIsMaker;
private long openingDate;
private final PubKeyRing traderPubKeyRing;
private final long tradeDate;
private final Contract contract;
@ -78,6 +75,8 @@ public final class Dispute implements NetworkPayload {
@Nullable
private String disputePayoutTxId;
private long openingDate;
transient private Storage<DisputeList> storage;
transient private ObservableList<DisputeCommunicationMessage> observableList;
transient private BooleanProperty isClosedProperty;
@ -125,6 +124,7 @@ public final class Dispute implements NetworkPayload {
isSupportTicket);
openingDate = new Date().getTime();
this.storage = storage;
}

View file

@ -42,10 +42,7 @@ import java.util.stream.Collectors;
@ToString
@Getter
public final class Mediator implements StoragePayload {
public static final long TTL = TimeUnit.DAYS.toMillis(10);
// Payload
private final long TTL = TimeUnit.DAYS.toMillis(10);
private final PubKeyRing pubKeyRing;
private final NodeAddress nodeAddress;
private final List<String> languageCodes;
@ -76,54 +73,44 @@ public final class Mediator implements StoragePayload {
this.nodeAddress = nodeAddress;
this.pubKeyRing = pubKeyRing;
this.languageCodes = languageCodes;
this.emailAddress = emailAddress;
this.info = info;
this.registrationDate = registrationDate.getTime();
this.registrationPubKey = registrationPubKey;
this.registrationSignature = registrationSignature;
this.emailAddress = emailAddress;
this.info = info;
this.extraDataMap = extraDataMap;
}
@Override
public long getTTL() {
return TTL;
public PB.StoragePayload toProtoMessage() {
final PB.Mediator.Builder builder = PB.Mediator.newBuilder()
.setNodeAddress(nodeAddress.toProtoMessage())
.setPubKeyRing(pubKeyRing.toProtoMessage())
.addAllLanguageCodes(languageCodes)
.setRegistrationDate(registrationDate)
.setRegistrationPubKey(ByteString.copyFrom(registrationPubKey))
.setRegistrationSignature(registrationSignature);
Optional.ofNullable(emailAddress).ifPresent(builder::setEmailAddress);
Optional.ofNullable(info).ifPresent(builder::setInfo);
Optional.ofNullable(extraDataMap).ifPresent(builder::putAllExtraData);
return PB.StoragePayload.newBuilder().setMediator(builder).build();
}
public static Mediator fromProto(PB.Mediator proto) {
return new Mediator(NodeAddress.fromProto(proto.getNodeAddress()),
PubKeyRing.fromProto(proto.getPubKeyRing()),
proto.getLanguageCodesList().stream().collect(Collectors.toList()),
new Date(proto.getRegistrationDate()),
proto.getRegistrationPubKey().toByteArray(),
proto.getRegistrationSignature(),
proto.getEmailAddress().isEmpty() ? null : proto.getEmailAddress(),
proto.getInfo().isEmpty() ? null : proto.getInfo(),
CollectionUtils.isEmpty(proto.getExtraDataMap()) ? null : proto.getExtraDataMap());
}
@Override
public PublicKey getOwnerPubKey() {
return pubKeyRing.getSignaturePubKey();
}
@Override
public PB.StoragePayload toProtoMessage() {
final PB.Mediator.Builder builder = PB.Mediator.newBuilder()
.setPubKeyRing(pubKeyRing.toProtoMessage())
.setNodeAddress(nodeAddress.toProtoMessage())
.addAllLanguageCodes(languageCodes)
.setRegistrationDate(registrationDate)
.setRegistrationSignature(registrationSignature)
.setRegistrationPubKey(ByteString.copyFrom(registrationPubKey));
Optional.ofNullable(extraDataMap).ifPresent(builder::putAllExtraDataMap);
Optional.ofNullable(emailAddress).ifPresent(builder::setEmailAddress);
Optional.ofNullable(info).ifPresent(builder::setInfo);
return PB.StoragePayload.newBuilder().setMediator(builder).build();
}
public static Mediator fromProto(PB.Mediator mediator) {
List<String> langCodes = mediator.getLanguageCodesList().stream().collect(Collectors.toList());
Date date = new Date(mediator.getRegistrationDate());
String emailAddress = mediator.getEmailAddress().isEmpty() ? null : mediator.getEmailAddress();
return new Mediator(NodeAddress.fromProto(mediator.getNodeAddress()),
PubKeyRing.fromProto(mediator.getPubKeyRing()),
langCodes,
date,
mediator.getRegistrationPubKey().toByteArray(),
mediator.getRegistrationSignature(),
emailAddress,
mediator.getInfo(),
CollectionUtils.isEmpty(mediator.getExtraDataMapMap()) ?
null : mediator.getExtraDataMapMap());
}
}

View file

@ -43,25 +43,22 @@ import java.util.concurrent.TimeUnit;
@Data
// TODO There will be another object for PersistableEnvelope
public final class CompensationRequestPayload implements LazyProcessedStoragePayload, PersistedStoragePayload, PersistableEnvelope {
public static final long TTL = TimeUnit.DAYS.toMillis(30);
private final byte version;
private final long creationDate;
private final long TTL = TimeUnit.DAYS.toMillis(30);
private final String uid;
private final String name;
private final String title;
private final String category;
private final String description;
private final String link;
public final long startDate;
public final long endDate;
private final long startDate;
private final long endDate;
private final long requestedBtc;
private final String btcAddress;
private final String nodeAddress;
@JsonExclude
private final byte[] p2pStorageSignaturePubKeyBytes;
private final byte[] ownerPubKeyBytes;
// used for json
private String p2pStorageSignaturePubKeyAsHex;
private String ownerPubPubKeyAsHex;
// Signature of the JSON data of this object excluding the signature and feeTxId fields using the standard Bitcoin
// messaging signing format as a base64 encoded string.
@JsonExclude
@ -75,12 +72,12 @@ public final class CompensationRequestPayload implements LazyProcessedStoragePay
@Nullable
private Map<String, String> extraDataMap;
private final byte version;
private final long creationDate;
// Domain
@JsonExclude
private transient PublicKey ownerPubKey;
// Called from domain
public CompensationRequestPayload(String uid,
String name,
String title,
@ -92,7 +89,7 @@ public final class CompensationRequestPayload implements LazyProcessedStoragePay
Coin requestedBtc,
String btcAddress,
NodeAddress nodeAddress,
PublicKey p2pStorageSignaturePubKey) {
PublicKey ownerPubKey) {
this(uid,
name,
title,
@ -104,28 +101,28 @@ public final class CompensationRequestPayload implements LazyProcessedStoragePay
requestedBtc,
btcAddress,
nodeAddress.getFullAddress(),
Sig.getSigPublicKeyBytes(p2pStorageSignaturePubKey),
Sig.getSigPublicKeyBytes(ownerPubKey),
null);
}
// Called from PB
public CompensationRequestPayload(String uid,
String name,
String title,
String category,
String description,
String link,
Date startDate,
Date endDate,
Coin requestedBtc,
String btcAddress,
String nodeAddress,
byte[] p2pStorageSignaturePubKeyBytes,
@Nullable Map<String, String> extraDataMap) {
version = Version.COMPENSATION_REQUEST_VERSION;
creationDate = new Date().getTime();
///////////////////////////////////////////////////////////////////////////////////////////
// PROTO BUFFER
///////////////////////////////////////////////////////////////////////////////////////////
private CompensationRequestPayload(String uid,
String name,
String title,
String category,
String description,
String link,
Date startDate,
Date endDate,
Coin requestedBtc,
String btcAddress,
String nodeAddress,
byte[] ownerPubKeyBytes,
@Nullable Map<String, String> extraDataMap) {
this.uid = uid;
this.name = name;
this.title = title;
@ -137,19 +134,57 @@ public final class CompensationRequestPayload implements LazyProcessedStoragePay
this.requestedBtc = requestedBtc.value;
this.btcAddress = btcAddress;
this.nodeAddress = nodeAddress;
this.p2pStorageSignaturePubKeyBytes = p2pStorageSignaturePubKeyBytes;
this.ownerPubKeyBytes = ownerPubKeyBytes;
this.extraDataMap = extraDataMap;
ownerPubKey = Sig.getSigPublicKeyFromBytes(p2pStorageSignaturePubKeyBytes);
p2pStorageSignaturePubKeyAsHex = Utils.HEX.encode(ownerPubKey.getEncoded());
version = Version.COMPENSATION_REQUEST_VERSION;
creationDate = new Date().getTime();
this.ownerPubKey = Sig.getSigPublicKeyFromBytes(ownerPubKeyBytes);
ownerPubPubKeyAsHex = Utils.HEX.encode(this.ownerPubKey.getEncoded());
}
@Override
public long getTTL() {
return TTL;
public PB.StoragePayload toProtoMessage() {
final PB.CompensationRequestPayload.Builder builder = PB.CompensationRequestPayload.newBuilder()
.setUid(uid)
.setName(name)
.setTitle(title)
.setCategory(category)
.setDescription(description)
.setLink(link)
.setStartDate(startDate)
.setEndDate(endDate)
.setRequestedBtc(requestedBtc)
.setBtcAddress(btcAddress)
.setNodeAddress(nodeAddress)
.setOwnerPubKeyAsHex(ownerPubPubKeyAsHex)
.setSignature(signature)
.setFeeTxId(feeTxId)
.setVersion(version)
.setCreationDate(creationDate);
Optional.ofNullable(extraDataMap).ifPresent(builder::putAllExtraData);
return PB.StoragePayload.newBuilder().setCompensationRequestPayload(builder).build();
}
public static CompensationRequestPayload fromProto(PB.CompensationRequestPayload proto) {
return new CompensationRequestPayload(proto.getUid(),
proto.getName(),
proto.getTitle(),
proto.getCategory(),
proto.getDescription(), proto.getLink(),
new Date(proto.getStartDate()),
new Date(proto.getEndDate()),
Coin.valueOf(proto.getRequestedBtc()),
proto.getBtcAddress(),
proto.getNodeAddress(), proto.getOwnerPubKeyBytes().toByteArray(),
CollectionUtils.isEmpty(proto.getExtraDataMap()) ? null : proto.getExtraDataMap());
}
///////////////////////////////////////////////////////////////////////////////////////////
// Getters
///////////////////////////////////////////////////////////////////////////////////////////
public Date getStartDate() {
return new Date(startDate);
}
@ -174,37 +209,6 @@ public final class CompensationRequestPayload implements LazyProcessedStoragePay
return uid.substring(0, 8);
}
@Override
public PB.StoragePayload toProtoMessage() {
final PB.CompensationRequestPayload.Builder builder = PB.CompensationRequestPayload.newBuilder()
.setVersion(version)
.setCreationDate(creationDate)
.setUid(uid)
.setName(name)
.setTitle(title)
.setCategory(category)
.setDescription(description)
.setLink(link)
.setStartDate(startDate)
.setEndDate(endDate)
.setRequestedBtc(requestedBtc)
.setBtcAddress(btcAddress)
.setNodeAddress(nodeAddress)
.setP2PStorageSignaturePubKeyAsHex(p2pStorageSignaturePubKeyAsHex)
.setSignature(signature)
.setFeeTxId(feeTxId);
Optional.ofNullable(extraDataMap).ifPresent(builder::putAllExtraDataMap);
return PB.StoragePayload.newBuilder().setCompensationRequestPayload(builder).build();
}
public static CompensationRequestPayload fromProto(PB.CompensationRequestPayload proto) {
return new CompensationRequestPayload(proto.getUid(), proto.getName(), proto.getTitle(), proto.getCategory(),
proto.getDescription(), proto.getLink(), new Date(proto.getStartDate()), new Date(proto.getEndDate()),
Coin.valueOf(proto.getRequestedBtc()), proto.getBtcAddress(),
proto.getNodeAddress(), proto.getP2PStorageSignaturePubKeyBytes().toByteArray(),
CollectionUtils.isEmpty(proto.getExtraDataMapMap()) ? null : proto.getExtraDataMapMap());
}
@Override
public String toString() {
return "CompensationRequestPayload{" +
@ -221,8 +225,8 @@ public final class CompensationRequestPayload implements LazyProcessedStoragePay
", requestedBtc=" + requestedBtc +
", btcAddress='" + btcAddress + '\'' +
", nodeAddress='" + getNodeAddress() + '\'' +
", p2pStorageSignaturePubKeyBytes=" + Hex.toHexString(p2pStorageSignaturePubKeyBytes) +
", p2pStorageSignaturePubKeyAsHex='" + p2pStorageSignaturePubKeyAsHex + '\'' +
", p2pStorageSignaturePubKeyBytes=" + Hex.toHexString(ownerPubKeyBytes) +
", p2pStorageSignaturePubKeyAsHex='" + ownerPubPubKeyAsHex + '\'' +
", signature='" + signature + '\'' +
", feeTxId='" + feeTxId + '\'' +
", extraDataMap=" + extraDataMap +

View file

@ -19,6 +19,9 @@ package io.bisq.core.dao.vote;
import io.bisq.common.proto.persistable.PersistablePayload;
import io.bisq.generated.protobuffer.PB;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Nullable;
@ -28,60 +31,32 @@ import static com.google.common.base.Preconditions.checkArgument;
//TODO if sent over wire make final
@Slf4j
@Getter
@ToString
@EqualsAndHashCode
public class VoteItem implements PersistablePayload {
// public final String version;
public final VotingType votingType;
private final VotingType votingType;
@Nullable
public final String name;
public final long defaultValue;
protected boolean hasVoted;
public byte getValue() {
return value;
}
private final String name;
private final long defaultValue;
private byte value;
public VoteItem(VotingType votingType, @Nullable String name, byte value, @Nullable VotingDefaultValues votingDefaultValues) {
this.votingType = votingType;
this.name = name;
this.value = value;
this.defaultValue = votingDefaultValues != null ? votingDefaultValues.getValueByVotingType(votingType) : 0;
}
private boolean hasVoted;
public VoteItem(VotingType votingType, String name, VotingDefaultValues votingDefaultValues) {
this(votingType, name, (byte) 0x00, votingDefaultValues);
}
public long getAdjustedValue(long originalValue, int change) {
checkArgument(change < 255 && change > -1,
"Range for change can be 0 to 254. 255 is not supported as we want a 0 value in the middle");
double fact = (change - 127) / 127d;
return (long) (originalValue * Math.pow(10, fact));
}
// We return the change parameter (0-254)
public int getChange(long originalValue, long newValue) {
return (int) Math.round(Math.log10((double) newValue / (double) originalValue) * 127 + 127);
}
///////////////////////////////////////////////////////////////////////////////////////////
// PROTO BUFFER
///////////////////////////////////////////////////////////////////////////////////////////
public void setValue(byte value) {
private VoteItem(VotingType votingType, @Nullable String name, byte value, @Nullable VotingDefaultValues votingDefaultValues) {
this.votingType = votingType;
this.name = name;
this.value = value;
this.hasVoted = true;
}
public boolean hasVoted() {
return hasVoted;
}
@Override
public String toString() {
return "VoteItem{" +
"code=" + votingType +
", name='" + name + '\'' +
", value=" + value +
'}';
this.defaultValue = votingDefaultValues != null ? votingDefaultValues.getValueByVotingType(votingType) : 0;
}
@Override
@ -99,6 +74,31 @@ public class VoteItem implements PersistablePayload {
VotingDefaultValues defaultValues = new VotingDefaultValues();
VotingType votingType = VotingType.valueOf(voteItem.getVotingType().name());
defaultValues.setValueByVotingType(votingType, voteItem.getValue());
return new VoteItem(votingType, voteItem.getName(), (byte) voteItem.getValue(), defaultValues);
return new VoteItem(votingType,
voteItem.getName(),
(byte) voteItem.getValue(),
defaultValues);
}
///////////////////////////////////////////////////////////////////////////////////////////
// API
///////////////////////////////////////////////////////////////////////////////////////////
public long getAdjustedValue(long originalValue, int change) {
checkArgument(change < 255 && change > -1,
"Range for change can be 0 to 254. 255 is not supported as we want a 0 value in the middle");
double fact = (change - 127) / 127d;
return (long) (originalValue * Math.pow(10, fact));
}
// We return the change parameter (0-254)
public int getChange(long originalValue, long newValue) {
return (int) Math.round(Math.log10((double) newValue / (double) originalValue) * 127 + 127);
}
public void setValue(byte value) {
this.value = value;
this.hasVoted = true;
}
}

View file

@ -99,7 +99,7 @@ public final class VoteItemsList implements PersistablePayload {
}
public Optional<VoteItem> getVoteItemByVotingType(VotingType votingType) {
return allVoteItemList.stream().filter(e -> e.votingType == votingType).findAny();
return allVoteItemList.stream().filter(e -> e.getVotingType() == votingType).findAny();
}
// TODO not impl yet

View file

@ -266,7 +266,7 @@ public class VotingManager {
items.stream().forEach(paramItem -> {
checkArgument(outputStream.size() % 2 == 0,
"Position of writing code must be at even index.");
outputStream.write(paramItem.votingType.code);
outputStream.write(paramItem.getVotingType().code);
byte value = paramItem.getValue();
outputStream.write(value);
});

View file

@ -17,17 +17,14 @@
package io.bisq.core.filter;
import com.google.common.collect.Maps;
import com.google.protobuf.ByteString;
import io.bisq.common.crypto.Sig;
import io.bisq.core.proto.ProtoUtil;
import io.bisq.generated.protobuffer.PB;
import io.bisq.network.p2p.storage.payload.StoragePayload;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.util.encoders.Hex;
import org.springframework.util.CollectionUtils;
import javax.annotation.Nullable;
@ -38,17 +35,18 @@ import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkNotNull;
@Slf4j
@Getter
@EqualsAndHashCode
@ToString
public final class Filter implements StoragePayload {
private static final long TTL = TimeUnit.DAYS.toMillis(21);
private final long TTL = TimeUnit.DAYS.toMillis(21);
private final List<String> bannedOfferIds;
private final List<String> bannedNodeAddress;
private final List<PaymentAccountFilter> bannedPaymentAccounts;
public final List<String> bannedNodeAddress;
public final List<String> bannedOfferIds;
public final List<PaymentAccountFilter> bannedPaymentAccounts;
private String signatureAsBase64;
private byte[] ownerPubKeyBytes;
// Should be only used in emergency case if we need to add data but do not want to break backward compatibility
@ -64,16 +62,22 @@ public final class Filter implements StoragePayload {
this.bannedOfferIds = bannedOfferIds;
this.bannedNodeAddress = bannedNodeAddress;
this.bannedPaymentAccounts = bannedPaymentAccounts;
this.extraDataMap = Maps.newHashMap();
}
///////////////////////////////////////////////////////////////////////////////////////////
// PROTO BUFFER
///////////////////////////////////////////////////////////////////////////////////////////
public Filter(List<String> bannedOfferIds,
List<String> bannedNodeAddress,
List<PaymentAccountFilter> bannedPaymentAccounts,
String signatureAsBase64,
byte[] ownerPubKeyBytes,
@Nullable Map<String, String> extraDataMap) {
this(bannedOfferIds, bannedNodeAddress, bannedPaymentAccounts);
this(bannedOfferIds,
bannedNodeAddress,
bannedPaymentAccounts);
this.signatureAsBase64 = signatureAsBase64;
this.ownerPubKeyBytes = ownerPubKeyBytes;
this.extraDataMap = extraDataMap;
@ -81,55 +85,44 @@ public final class Filter implements StoragePayload {
ownerPubKey = Sig.getSigPublicKeyFromBytes(ownerPubKeyBytes);
}
@Override
public PB.StoragePayload toProtoMessage() {
checkNotNull(signatureAsBase64, "signatureAsBase64 must nto be null");
checkNotNull(ownerPubKeyBytes, "ownerPubKeyBytes must nto be null");
List<PB.PaymentAccountFilter> paymentAccountFilterList = bannedPaymentAccounts.stream()
.map(PaymentAccountFilter::toProtoMessage)
.collect(Collectors.toList());
final PB.Filter.Builder builder = PB.Filter.newBuilder()
.addAllBannedOfferIds(bannedOfferIds)
.addAllBannedNodeAddress(bannedNodeAddress)
.addAllBannedPaymentAccounts(paymentAccountFilterList)
.setSignatureAsBase64(signatureAsBase64)
.setOwnerPubKeyBytes(ByteString.copyFrom(ownerPubKeyBytes));
Optional.ofNullable(extraDataMap).ifPresent(builder::putAllExtraData);
return PB.StoragePayload.newBuilder().setFilter(builder).build();
}
public static Filter fromProto(PB.Filter proto) {
return new Filter(proto.getBannedOfferIdsList().stream().collect(Collectors.toList()),
proto.getBannedNodeAddressList().stream().collect(Collectors.toList()),
proto.getBannedPaymentAccountsList()
.stream()
.map(PaymentAccountFilter::fromProto)
.collect(Collectors.toList()),
proto.getSignatureAsBase64(),
proto.getOwnerPubKeyBytes().toByteArray(),
CollectionUtils.isEmpty(proto.getExtraDataMap()) ? null : proto.getExtraDataMap());
}
///////////////////////////////////////////////////////////////////////////////////////////
// API
///////////////////////////////////////////////////////////////////////////////////////////
public void setSigAndPubKey(String signatureAsBase64, PublicKey ownerPubKey) {
this.signatureAsBase64 = signatureAsBase64;
this.ownerPubKey = ownerPubKey;
ownerPubKeyBytes = Sig.getSigPublicKeyBytes(this.ownerPubKey);
}
@Override
public long getTTL() {
return TTL;
}
@Override
public PB.StoragePayload toProtoMessage() {
List<PB.PaymentAccountFilter> paymentAccountFilterList;
paymentAccountFilterList = bannedPaymentAccounts.stream()
.map(PaymentAccountFilter::toProtoBuf).collect(Collectors.toList());
final PB.Filter.Builder builder = PB.Filter.newBuilder()
.addAllBannedNodeAddress(bannedNodeAddress)
.addAllBannedOfferIds(bannedOfferIds)
.addAllBannedPaymentAccounts(paymentAccountFilterList)
.setSignatureAsBase64(signatureAsBase64)
.setOwnerPubKeyBytes(ByteString.copyFrom(ownerPubKeyBytes));
Optional.ofNullable(extraDataMap).ifPresent(builder::putAllExtraDataMap);
return PB.StoragePayload.newBuilder().setFilter(builder).build();
}
public static Filter fromProto(PB.Filter filter) {
List<PaymentAccountFilter> paymentAccountFilters = filter.getBannedPaymentAccountsList()
.stream().map(accountFilter -> ProtoUtil.getPaymentAccountFilter(accountFilter)).collect(Collectors.toList());
return new Filter(filter.getBannedOfferIdsList().stream().collect(Collectors.toList()),
filter.getBannedNodeAddressList().stream().collect(Collectors.toList()),
paymentAccountFilters,
filter.getSignatureAsBase64(),
filter.getOwnerPubKeyBytes().toByteArray(),
CollectionUtils.isEmpty(filter.getExtraDataMapMap()) ?
null : filter.getExtraDataMapMap());
}
@Override
public String toString() {
return "Filter{" +
"bannedNodeAddress=" + bannedNodeAddress +
", bannedOfferIds=" + bannedOfferIds +
", bannedPaymentAccounts=" + bannedPaymentAccounts +
", signatureAsBase64='" + signatureAsBase64 + '\'' +
", publicKey=" + Hex.toHexString(ownerPubKey.getEncoded()) +
", extraDataMap=" + extraDataMap +
'}';
}
}

View file

@ -162,10 +162,10 @@ public class FilterManager {
}
private String getHexFromData(Filter filter) {
PB.Filter.Builder builder = PB.Filter.newBuilder().addAllBannedNodeAddress(filter.bannedNodeAddress)
.addAllBannedOfferIds(filter.bannedOfferIds)
.addAllBannedPaymentAccounts(filter.bannedPaymentAccounts.stream()
.map(PaymentAccountFilter::toProtoBuf)
PB.Filter.Builder builder = PB.Filter.newBuilder().addAllBannedNodeAddress(filter.getBannedNodeAddress())
.addAllBannedOfferIds(filter.getBannedOfferIds())
.addAllBannedPaymentAccounts(filter.getBannedPaymentAccounts().stream()
.map(PaymentAccountFilter::toProtoMessage)
.collect(Collectors.toList()));
return Utils.HEX.encode(builder.build().toByteArray());
}

View file

@ -1,19 +1,16 @@
package io.bisq.core.filter;
import io.bisq.common.proto.network.NetworkPayload;
import io.bisq.generated.protobuffer.PB;
import lombok.ToString;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import java.io.Serializable;
@ToString
@Value
@Slf4j
public class PaymentAccountFilter implements Serializable {
// Payload
public final String paymentMethodId;
public final String getMethodName;
public final String value;
public class PaymentAccountFilter implements NetworkPayload {
private final String paymentMethodId;
private final String getMethodName;
private final String value;
public PaymentAccountFilter(String paymentMethodId, String getMethodName, String value) {
this.paymentMethodId = paymentMethodId;
@ -21,10 +18,18 @@ public class PaymentAccountFilter implements Serializable {
this.value = value;
}
public PB.PaymentAccountFilter toProtoBuf() {
@Override
public PB.PaymentAccountFilter toProtoMessage() {
return PB.PaymentAccountFilter.newBuilder()
.setPaymentMethodId(paymentMethodId)
.setGetMethodName(getMethodName)
.setValue(value).build();
.setValue(value)
.build();
}
public static PaymentAccountFilter fromProto(PB.PaymentAccountFilter proto) {
return new PaymentAccountFilter(proto.getPaymentMethodId(),
proto.getGetMethodName(),
proto.getValue());
}
}

View file

@ -86,6 +86,21 @@ public class Offer implements NetworkPayload, PersistablePayload {
this.offerPayload = offerPayload;
}
///////////////////////////////////////////////////////////////////////////////////////////
// PROTO BUFFER
///////////////////////////////////////////////////////////////////////////////////////////
@Override
public PB.Offer toProtoMessage() {
return PB.Offer.newBuilder().setOfferPayload(offerPayload.toProtoMessage().getOfferPayload()).build();
}
public static Offer fromProto(PB.Offer proto) {
return new Offer(OfferPayload.fromProto(proto.getOfferPayload()));
}
///////////////////////////////////////////////////////////////////////////////////////////
// Availability
///////////////////////////////////////////////////////////////////////////////////////////
@ -364,7 +379,7 @@ public class Offer implements NetworkPayload, PersistablePayload {
}
public NodeAddress getMakerNodeAddress() {
return offerPayload.getMakerNodeAddress();
return offerPayload.getOwnerNodeAddress();
}
public PubKeyRing getPubKeyRing() {
@ -459,13 +474,4 @@ public class Offer implements NetworkPayload, PersistablePayload {
", offerPayload=" + offerPayload +
'}';
}
@Override
public PB.Offer toProtoMessage() {
return PB.Offer.newBuilder().setOfferPayload(offerPayload.toProtoMessage().getOfferPayload()).build();
}
public static Offer fromProto(PB.Offer proto) {
return new Offer(OfferPayload.fromProto(proto.getOfferPayload()));
}
}

View file

@ -17,7 +17,6 @@
package io.bisq.core.offer;
import io.bisq.common.app.DevEnv;
import io.bisq.common.app.Version;
import io.bisq.common.crypto.PubKeyRing;
import io.bisq.common.locale.CurrencyUtil;
@ -42,30 +41,30 @@ import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkArgument;
@ToString
@EqualsAndHashCode
@Getter
@Slf4j
public final class OfferPayload implements StoragePayload, RequiresOwnerIsOnlinePayload {
public static final long TTL = TimeUnit.MINUTES.toMillis(DevEnv.STRESS_TEST_MODE ? 6 : 6);
///////////////////////////////////////////////////////////////////////////////////////////
// Enums
///////////////////////////////////////////////////////////////////////////////////////////
public enum Direction {
BUY, SELL;
public static OfferPayload.Direction fromProto(PB.OfferPayload.Direction direction) {
return OfferPayload.Direction.valueOf(direction.name());
}
public static PB.OfferPayload.Direction toProtoMessage(Direction direction) {
return PB.OfferPayload.Direction.valueOf(direction.name());
}
}
///////////////////////////////////////////////////////////////////////////////////////////
// Instance fields
///////////////////////////////////////////////////////////////////////////////////////////
private final long TTL = TimeUnit.MINUTES.toMillis(6);
private final Direction direction;
private final String baseCurrencyCode;
private final String counterCurrencyCode;
@ -82,7 +81,6 @@ public final class OfferPayload implements StoragePayload, RequiresOwnerIsOnline
private final List<NodeAddress> mediatorNodeAddresses;
private final String id;
private final long date;
private final long protocolVersion;
// We use 2 type of prices: fixed price or price based on distance from market price
private final boolean useMarketBasedPrice;
@ -97,7 +95,7 @@ public final class OfferPayload implements StoragePayload, RequiresOwnerIsOnline
private final double marketPriceMargin;
private final long amount;
private final long minAmount;
private final NodeAddress makerNodeAddress;
private final NodeAddress ownerNodeAddress;
@JsonExclude
private final PubKeyRing pubKeyRing;
private final String makerPaymentAccountId;
@ -136,7 +134,8 @@ public final class OfferPayload implements StoragePayload, RequiresOwnerIsOnline
// at the P2P network storage checks. The hash of the object will be used to verify if the data is valid. Any new
// field in a class would break that hash and therefore break the storage mechanism.
@Nullable
private Map<String, String> extraDataMap;
private final Map<String, String> extraDataMap;
private final long protocolVersion;
///////////////////////////////////////////////////////////////////////////////////////////
@ -145,7 +144,7 @@ public final class OfferPayload implements StoragePayload, RequiresOwnerIsOnline
public OfferPayload(String id,
long date,
NodeAddress makerNodeAddress,
NodeAddress ownerNodeAddress,
PubKeyRing pubKeyRing,
Direction direction,
long price,
@ -183,7 +182,7 @@ public final class OfferPayload implements StoragePayload, RequiresOwnerIsOnline
this.id = id;
this.date = date;
this.makerNodeAddress = makerNodeAddress;
this.ownerNodeAddress = ownerNodeAddress;
this.pubKeyRing = pubKeyRing;
this.direction = direction;
this.price = price;
@ -219,38 +218,7 @@ public final class OfferPayload implements StoragePayload, RequiresOwnerIsOnline
this.hashOfChallenge = hashOfChallenge;
this.extraDataMap = extraDataMap;
this.protocolVersion = Version.TRADE_PROTOCOL_VERSION;
}
///////////////////////////////////////////////////////////////////////////////////////////
// Overridden Getters
///////////////////////////////////////////////////////////////////////////////////////////
@Override
public NodeAddress getOwnerNodeAddress() {
return makerNodeAddress;
}
@Override
public PublicKey getOwnerPubKey() {
return pubKeyRing.getSignaturePubKey();
}
@Override
public long getTTL() {
return TTL;
}
//TODO remove
public String getCurrencyCode() {
if (CurrencyUtil.isCryptoCurrency(getBaseCurrencyCode()))
return getBaseCurrencyCode();
else
return getCounterCurrencyCode();
protocolVersion = Version.TRADE_PROTOCOL_VERSION;
}
@ -260,29 +228,26 @@ public final class OfferPayload implements StoragePayload, RequiresOwnerIsOnline
@Override
public PB.StoragePayload toProtoMessage() {
List<PB.NodeAddress> arbitratorNodeAddresses = this.arbitratorNodeAddresses.stream()
.map(NodeAddress::toProtoMessage)
.collect(Collectors.toList());
List<PB.NodeAddress> mediatorNodeAddresses = this.mediatorNodeAddresses.stream()
.map(NodeAddress::toProtoMessage)
.collect(Collectors.toList());
PB.OfferPayload.Builder offerBuilder = PB.OfferPayload.newBuilder()
.setDirection(PB.OfferPayload.Direction.valueOf(direction.name()))
.setBaseCurrencyCode(baseCurrencyCode)
.setCounterCurrencyCode(counterCurrencyCode)
.setPaymentMethodId(paymentMethodId)
.addAllArbitratorNodeAddresses(arbitratorNodeAddresses)
.addAllMediatorNodeAddresses(mediatorNodeAddresses)
PB.OfferPayload.Builder builder = PB.OfferPayload.newBuilder()
.setId(id)
.setDate(date)
.setProtocolVersion(protocolVersion)
.setUseMarketBasedPrice(useMarketBasedPrice)
.setOwnerNodeAddress(ownerNodeAddress.toProtoMessage())
.setPubKeyRing(pubKeyRing.toProtoMessage())
.setDirection(Direction.toProtoMessage(direction))
.setPrice(price)
.setMarketPriceMargin(marketPriceMargin)
.setUseMarketBasedPrice(useMarketBasedPrice)
.setAmount(amount)
.setMinAmount(minAmount)
.setMakerNodeAddress(makerNodeAddress.toProtoMessage())
.setPubKeyRing(pubKeyRing.toProtoMessage())
.setBaseCurrencyCode(baseCurrencyCode)
.setCounterCurrencyCode(counterCurrencyCode)
.addAllArbitratorNodeAddresses(arbitratorNodeAddresses.stream()
.map(NodeAddress::toProtoMessage)
.collect(Collectors.toList()))
.addAllMediatorNodeAddresses(mediatorNodeAddresses.stream()
.map(NodeAddress::toProtoMessage)
.collect(Collectors.toList()))
.setPaymentMethodId(paymentMethodId)
.setMakerPaymentAccountId(makerPaymentAccountId)
.setVersionNr(versionNr)
.setBlockHeightAtOfferCreation(blockHeightAtOfferCreation)
@ -297,49 +262,39 @@ public final class OfferPayload implements StoragePayload, RequiresOwnerIsOnline
.setUseReOpenAfterAutoClose(useReOpenAfterAutoClose)
.setLowerClosePrice(lowerClosePrice)
.setUpperClosePrice(upperClosePrice)
.setIsPrivateOffer(isPrivateOffer);
.setIsPrivateOffer(isPrivateOffer)
.setProtocolVersion(protocolVersion);
if (Objects.nonNull(offerFeePaymentTxId)) {
offerBuilder.setOfferFeePaymentTxId(offerFeePaymentTxId);
builder.setOfferFeePaymentTxId(offerFeePaymentTxId);
} else {
throw new RuntimeException("OfferPayload is in invalid state: offerFeePaymentTxID is not set when adding to P2P network.");
}
Optional.ofNullable(countryCode).ifPresent(offerBuilder::setCountryCode);
Optional.ofNullable(bankId).ifPresent(offerBuilder::setBankId);
Optional.ofNullable(acceptedBankIds).ifPresent(offerBuilder::addAllAcceptedBankIds);
Optional.ofNullable(hashOfChallenge).ifPresent(offerBuilder::setHashOfChallenge);
Optional.ofNullable(acceptedCountryCodes).ifPresent(offerBuilder::addAllAcceptedCountryCodes);
Optional.ofNullable(extraDataMap).ifPresent(offerBuilder::putAllExtraDataMap);
Optional.ofNullable(countryCode).ifPresent(builder::setCountryCode);
Optional.ofNullable(bankId).ifPresent(builder::setBankId);
Optional.ofNullable(acceptedBankIds).ifPresent(builder::addAllAcceptedBankIds);
Optional.ofNullable(acceptedCountryCodes).ifPresent(builder::addAllAcceptedCountryCodes);
Optional.ofNullable(hashOfChallenge).ifPresent(builder::setHashOfChallenge);
Optional.ofNullable(extraDataMap).ifPresent(builder::putAllExtraData);
return PB.StoragePayload.newBuilder().setOfferPayload(offerBuilder).build();
return PB.StoragePayload.newBuilder().setOfferPayload(builder).build();
}
public static OfferPayload fromProto(PB.OfferPayload proto) {
List<NodeAddress> arbitratorNodeAddresses = proto.getArbitratorNodeAddressesList().stream()
.map(NodeAddress::fromProto).collect(Collectors.toList());
List<NodeAddress> mediatorNodeAddresses = proto.getMediatorNodeAddressesList().stream()
.map(NodeAddress::fromProto).collect(Collectors.toList());
// Nullable object need to be checked against the default values in PB (not nice... ;-( )
// convert these lists because otherwise when they're empty they are lazyStringArrayList objects and NOT serializable,
// which is needed for the P2PStorage getHash() operation
List<String> acceptedCountryCodes = proto.getAcceptedCountryCodesList().isEmpty() ?
null : proto.getAcceptedCountryCodesList().stream().collect(Collectors.toList());
checkArgument(proto.getOfferFeePaymentTxId().isEmpty(), "OfferFeePaymentTxId must be set in PB.OfferPayload");
String countryCode = proto.getCountryCode().isEmpty() ? null : proto.getCountryCode();
String bankId = proto.getBankId().isEmpty() ? null : proto.getBankId();
List<String> acceptedBankIds = proto.getAcceptedBankIdsList().isEmpty() ?
null : proto.getAcceptedBankIdsList().stream().collect(Collectors.toList());
Map<String, String> extraDataMapMap = CollectionUtils.isEmpty(proto.getExtraDataMapMap()) ?
null : proto.getExtraDataMapMap();
final String countryCode1 = proto.getCountryCode();
String countryCode = countryCode1.isEmpty() ? null : countryCode1;
String bankId = proto.getBankId().isEmpty() ? null : proto.getBankId();
String offerFeePaymentTxId = proto.getOfferFeePaymentTxId().isEmpty() ? null : proto.getOfferFeePaymentTxId();
List<String> acceptedCountryCodes = proto.getAcceptedCountryCodesList().isEmpty() ?
null : proto.getAcceptedCountryCodesList().stream().collect(Collectors.toList());
String hashOfChallenge = proto.getHashOfChallenge().isEmpty() ? null : proto.getHashOfChallenge();
Map<String, String> extraDataMapMap = CollectionUtils.isEmpty(proto.getExtraDataMap()) ?
null : proto.getExtraDataMap();
return new OfferPayload(proto.getId(),
proto.getDate(),
NodeAddress.fromProto(proto.getMakerNodeAddress()),
NodeAddress.fromProto(proto.getOwnerNodeAddress()),
PubKeyRing.fromProto(proto.getPubKeyRing()),
OfferPayload.Direction.fromProto(proto.getDirection()),
proto.getPrice(),
@ -349,11 +304,15 @@ public final class OfferPayload implements StoragePayload, RequiresOwnerIsOnline
proto.getMinAmount(),
proto.getBaseCurrencyCode(),
proto.getCounterCurrencyCode(),
arbitratorNodeAddresses,
mediatorNodeAddresses,
proto.getArbitratorNodeAddressesList().stream()
.map(NodeAddress::fromProto)
.collect(Collectors.toList()),
proto.getMediatorNodeAddressesList().stream()
.map(NodeAddress::fromProto)
.collect(Collectors.toList()),
proto.getPaymentMethodId(),
proto.getMakerPaymentAccountId(),
offerFeePaymentTxId,
proto.getOfferFeePaymentTxId(),
countryCode,
acceptedCountryCodes,
bankId,
@ -375,4 +334,27 @@ public final class OfferPayload implements StoragePayload, RequiresOwnerIsOnline
hashOfChallenge,
extraDataMapMap);
}
///////////////////////////////////////////////////////////////////////////////////////////
// API
///////////////////////////////////////////////////////////////////////////////////////////
@Override
public PublicKey getOwnerPubKey() {
return pubKeyRing.getSignaturePubKey();
}
// In the offer we support base and counter currency
// Fiat offers have base currency BTC and counterCurrency Fiat
// Altcoins have base currency Altcoin and counterCurrency BTC
// The rest of the app does not support yet that concept of base currency and counter currencies
// so we map here for convenience
public String getCurrencyCode() {
if (CurrencyUtil.isCryptoCurrency(getBaseCurrencyCode()))
return getBaseCurrencyCode();
else
return getCounterCurrencyCode();
}
}

View file

@ -62,11 +62,10 @@ public final class OpenOffer implements Tradable {
@Override
public Message toProtoMessage() {
final PB.OpenOffer build = PB.OpenOffer.newBuilder()
return PB.OpenOffer.newBuilder()
.setOffer(offer.toProtoMessage())
.setState(PB.OpenOffer.State.valueOf(state.name()))
.build();
return build;
}
public static Tradable fromProto(PB.OpenOffer proto, Storage<TradableList<OpenOffer>> storage) {

View file

@ -22,12 +22,14 @@ import io.bisq.common.crypto.PubKeyRing;
import io.bisq.common.proto.network.NetworkEnvelope;
import io.bisq.generated.protobuffer.PB;
import io.bisq.network.p2p.SupportedCapabilitiesMessage;
import lombok.EqualsAndHashCode;
import lombok.Value;
import java.util.ArrayList;
// We add here the SupportedCapabilitiesMessage interface as that message always predates a direct connection
// to the trading peer
@EqualsAndHashCode(callSuper = true)
@Value
public final class OfferAvailabilityRequest extends OfferMessage implements SupportedCapabilitiesMessage {
private final PubKeyRing pubKeyRing;

View file

@ -23,12 +23,14 @@ import io.bisq.common.proto.network.NetworkEnvelope;
import io.bisq.core.offer.AvailabilityResult;
import io.bisq.generated.protobuffer.PB;
import io.bisq.network.p2p.SupportedCapabilitiesMessage;
import lombok.EqualsAndHashCode;
import lombok.Value;
import java.util.ArrayList;
// We add here the SupportedCapabilitiesMessage interface as that message always predates a direct connection
// to the trading peer
@EqualsAndHashCode(callSuper = true)
@Value
public final class OfferAvailabilityResponse extends OfferMessage implements SupportedCapabilitiesMessage {
private final AvailabilityResult availabilityResult;

View file

@ -35,26 +35,23 @@ import java.util.stream.Collectors;
@EqualsAndHashCode
@ToString
@Getter
@Slf4j
public abstract class PaymentAccount implements PersistablePayload {
@Getter
protected final String id;
protected final long creationDate;
@Getter
protected final PaymentMethod paymentMethod;
@Getter
@Setter
protected String accountName;
@Getter
final List<TradeCurrency> tradeCurrencies = new ArrayList<>();
@Getter
@Setter
protected TradeCurrency selectedTradeCurrency;
@Getter
protected final String id;
protected final long creationDate;
@Setter
public PaymentAccountPayload paymentAccountPayload;
@Setter
protected String accountName;
protected final List<TradeCurrency> tradeCurrencies = new ArrayList<>();
@Setter
protected TradeCurrency selectedTradeCurrency;
///////////////////////////////////////////////////////////////////////////////////////////
// Constructor
///////////////////////////////////////////////////////////////////////////////////////////
@ -67,6 +64,33 @@ public abstract class PaymentAccount implements PersistablePayload {
}
///////////////////////////////////////////////////////////////////////////////////////////
// PROTO BUFFER
///////////////////////////////////////////////////////////////////////////////////////////
@Override
public PB.PaymentAccount toProtoMessage() {
PB.PaymentAccount.Builder builder = PB.PaymentAccount.newBuilder()
.setPaymentMethod(paymentMethod.toProtoMessage())
.setId(paymentMethod.getId())
.setCreationDate(creationDate)
.setPaymentAccountPayload((PB.PaymentAccountPayload) paymentAccountPayload.toProtoMessage())
.setAccountName(accountName)
.addAllTradeCurrencies(ProtoCollectionUtil.<PB.TradeCurrency>collectionToProto(tradeCurrencies));
Optional.ofNullable(selectedTradeCurrency).ifPresent(selectedTradeCurrency -> builder.setSelectedTradeCurrency((PB.TradeCurrency) selectedTradeCurrency.toProtoMessage()));
return builder.build();
}
public static PaymentAccount fromProto(PB.PaymentAccount proto) {
PaymentAccount paymentAccount = PaymentAccountFactory.getPaymentAccount(PaymentMethod.getPaymentMethodById(proto.getPaymentMethod().getId()));
paymentAccount.setAccountName(proto.getAccountName());
paymentAccount.getTradeCurrencies().addAll(proto.getTradeCurrenciesList().stream().map(TradeCurrency::fromProto).collect(Collectors.toList()));
paymentAccount.setSelectedTradeCurrency(paymentAccount.getSelectedTradeCurrency());
paymentAccount.setPaymentAccountPayload(PaymentAccountPayload.fromProto(proto.getPaymentAccountPayload()));
return paymentAccount;
}
///////////////////////////////////////////////////////////////////////////////////////////
// API
///////////////////////////////////////////////////////////////////////////////////////////
@ -109,28 +133,4 @@ public abstract class PaymentAccount implements PersistablePayload {
///////////////////////////////////////////////////////////////////////////////////////////
protected abstract PaymentAccountPayload getPayload();
@Override
public PB.PaymentAccount toProtoMessage() {
PB.PaymentAccount.Builder builder = PB.PaymentAccount.newBuilder()
.setId(paymentMethod.getId())
.setCreationDate(creationDate)
.setPaymentMethod(paymentMethod.toProtoMessage())
.setAccountName(accountName)
.addAllTradeCurrencies(ProtoCollectionUtil.collectionToProto(tradeCurrencies))
.setPaymentAccountPayload((PB.PaymentAccountPayload) paymentAccountPayload.toProtoMessage());
Optional.ofNullable(selectedTradeCurrency).ifPresent(selectedTradeCurrency -> builder.setSelectedTradeCurrency((PB.TradeCurrency) selectedTradeCurrency.toProtoMessage()));
return builder.build();
}
// complicated: uses a factory to get the specific type, which then calls the ctor which does getPayload for id etc
public static PaymentAccount fromProto(PB.PaymentAccount account) {
PaymentAccount paymentAccount = PaymentAccountFactory.getPaymentAccount(PaymentMethod.getPaymentMethodById(account.getPaymentMethod().getId()));
paymentAccount.setAccountName(account.getAccountName());
paymentAccount.getTradeCurrencies().addAll(account.getTradeCurrenciesList().stream().map(tradeCurrency -> TradeCurrency.fromProto(tradeCurrency)).collect(Collectors.toList()));
paymentAccount.setSelectedTradeCurrency(paymentAccount.getSelectedTradeCurrency());
paymentAccount.setPaymentAccountPayload(PaymentAccountPayload.fromProto(account.getPaymentAccountPayload()));
return paymentAccount;
}
}

View file

@ -19,7 +19,7 @@ package io.bisq.core.payment.payload;
import io.bisq.common.locale.CountryUtil;
import io.bisq.common.proto.network.NetworkPayload;
import io.bisq.core.proto.ProtoUtil;
import io.bisq.core.proto.ProtoCoreUtil;
import io.bisq.generated.protobuffer.PB;
import lombok.EqualsAndHashCode;
import lombok.Getter;
@ -56,101 +56,101 @@ public abstract class PaymentAccountPayload implements NetworkPayload {
abstract public String getPaymentDetailsForTradePopup();
public static PaymentAccountPayload fromProto(PB.PaymentAccountPayload protoEntry) {
public static PaymentAccountPayload fromProto(PB.PaymentAccountPayload proto) {
PaymentAccountPayload result = null;
switch (protoEntry.getMessageCase()) {
switch (proto.getMessageCase()) {
case ALI_PAY_ACCOUNT_PAYLOAD:
result = new AliPayAccountPayload(protoEntry.getPaymentMethodId(), protoEntry.getId(),
protoEntry.getMaxTradePeriod(), protoEntry.getAliPayAccountPayload().getAccountNr());
result = new AliPayAccountPayload(proto.getPaymentMethodId(), proto.getId(),
proto.getMaxTradePeriod(), proto.getAliPayAccountPayload().getAccountNr());
break;
case CHASE_QUICK_PAY_ACCOUNT_PAYLOAD:
result = new ChaseQuickPayAccountPayload(protoEntry.getPaymentMethodId(), protoEntry.getId(),
protoEntry.getMaxTradePeriod(), protoEntry.getChaseQuickPayAccountPayload().getEmail(),
protoEntry.getChaseQuickPayAccountPayload().getHolderName());
result = new ChaseQuickPayAccountPayload(proto.getPaymentMethodId(), proto.getId(),
proto.getMaxTradePeriod(), proto.getChaseQuickPayAccountPayload().getEmail(),
proto.getChaseQuickPayAccountPayload().getHolderName());
break;
case CLEAR_XCHANGE_ACCOUNT_PAYLOAD:
result = new ClearXchangeAccountPayload(protoEntry.getPaymentMethodId(), protoEntry.getId(),
protoEntry.getMaxTradePeriod(), protoEntry.getClearXchangeAccountPayload().getHolderName(),
protoEntry.getClearXchangeAccountPayloadOrBuilder().getEmailOrMobileNr());
result = new ClearXchangeAccountPayload(proto.getPaymentMethodId(), proto.getId(),
proto.getMaxTradePeriod(), proto.getClearXchangeAccountPayload().getHolderName(),
proto.getClearXchangeAccountPayloadOrBuilder().getEmailOrMobileNr());
break;
case COUNTRY_BASED_PAYMENT_ACCOUNT_PAYLOAD:
switch (protoEntry.getCountryBasedPaymentAccountPayload().getMessageCase()) {
switch (proto.getCountryBasedPaymentAccountPayload().getMessageCase()) {
case BANK_ACCOUNT_PAYLOAD:
switch (protoEntry.getCountryBasedPaymentAccountPayload().getBankAccountPayload().getMessageCase()) {
switch (proto.getCountryBasedPaymentAccountPayload().getBankAccountPayload().getMessageCase()) {
case NATIONAL_BANK_ACCOUNT_PAYLOAD:
NationalBankAccountPayload nationalBankAccountPayload = new NationalBankAccountPayload(protoEntry.getPaymentMethodId(), protoEntry.getId(),
protoEntry.getMaxTradePeriod());
ProtoUtil.fillInBankAccountPayload(protoEntry, nationalBankAccountPayload);
ProtoUtil.fillInCountryBasedPaymentAccountPayload(protoEntry, nationalBankAccountPayload);
NationalBankAccountPayload nationalBankAccountPayload = new NationalBankAccountPayload(proto.getPaymentMethodId(), proto.getId(),
proto.getMaxTradePeriod());
ProtoCoreUtil.fillInBankAccountPayload(proto, nationalBankAccountPayload);
ProtoCoreUtil.fillInCountryBasedPaymentAccountPayload(proto, nationalBankAccountPayload);
result = nationalBankAccountPayload;
break;
case SAME_BANK_ACCONT_PAYLOAD:
SameBankAccountPayload sameBankAccountPayload = new SameBankAccountPayload(protoEntry.getPaymentMethodId(), protoEntry.getId(),
protoEntry.getMaxTradePeriod());
ProtoUtil.fillInBankAccountPayload(protoEntry, sameBankAccountPayload);
ProtoUtil.fillInCountryBasedPaymentAccountPayload(protoEntry, sameBankAccountPayload);
SameBankAccountPayload sameBankAccountPayload = new SameBankAccountPayload(proto.getPaymentMethodId(), proto.getId(),
proto.getMaxTradePeriod());
ProtoCoreUtil.fillInBankAccountPayload(proto, sameBankAccountPayload);
ProtoCoreUtil.fillInCountryBasedPaymentAccountPayload(proto, sameBankAccountPayload);
result = sameBankAccountPayload;
break;
case SPECIFIC_BANKS_ACCOUNT_PAYLOAD:
SpecificBanksAccountPayload specificBanksAccountPayload = new SpecificBanksAccountPayload(protoEntry.getPaymentMethodId(), protoEntry.getId(),
protoEntry.getMaxTradePeriod());
ProtoUtil.fillInBankAccountPayload(protoEntry, specificBanksAccountPayload);
ProtoUtil.fillInCountryBasedPaymentAccountPayload(protoEntry, specificBanksAccountPayload);
SpecificBanksAccountPayload specificBanksAccountPayload = new SpecificBanksAccountPayload(proto.getPaymentMethodId(), proto.getId(),
proto.getMaxTradePeriod());
ProtoCoreUtil.fillInBankAccountPayload(proto, specificBanksAccountPayload);
ProtoCoreUtil.fillInCountryBasedPaymentAccountPayload(proto, specificBanksAccountPayload);
result = specificBanksAccountPayload;
break;
}
break;
case CASH_DEPOSIT_ACCOUNT_PAYLOAD:
CashDepositAccountPayload cashDepositAccountPayload = new CashDepositAccountPayload(protoEntry.getPaymentMethodId(), protoEntry.getId(),
protoEntry.getMaxTradePeriod());
ProtoUtil.fillInCountryBasedPaymentAccountPayload(protoEntry, cashDepositAccountPayload);
CashDepositAccountPayload cashDepositAccountPayload = new CashDepositAccountPayload(proto.getPaymentMethodId(), proto.getId(),
proto.getMaxTradePeriod());
ProtoCoreUtil.fillInCountryBasedPaymentAccountPayload(proto, cashDepositAccountPayload);
result = cashDepositAccountPayload;
break;
case SEPA_ACCOUNT_PAYLOAD:
SepaAccountPayload sepaAccountPayload = new SepaAccountPayload(protoEntry.getPaymentMethodId(), protoEntry.getId(),
protoEntry.getMaxTradePeriod(), CountryUtil.getAllSepaCountries());
ProtoUtil.fillInCountryBasedPaymentAccountPayload(protoEntry, sepaAccountPayload);
SepaAccountPayload sepaAccountPayload = new SepaAccountPayload(proto.getPaymentMethodId(), proto.getId(),
proto.getMaxTradePeriod(), CountryUtil.getAllSepaCountries());
ProtoCoreUtil.fillInCountryBasedPaymentAccountPayload(proto, sepaAccountPayload);
result = sepaAccountPayload;
break;
}
break;
case CRYPTO_CURRENCY_ACCOUNT_PAYLOAD:
result = new CryptoCurrencyAccountPayload(protoEntry.getPaymentMethodId(), protoEntry.getId(),
protoEntry.getMaxTradePeriod(), protoEntry.getCryptoCurrencyAccountPayload().getAddress());
result = new CryptoCurrencyAccountPayload(proto.getPaymentMethodId(), proto.getId(),
proto.getMaxTradePeriod(), proto.getCryptoCurrencyAccountPayload().getAddress());
break;
case FASTER_PAYMENTS_ACCOUNT_PAYLOAD:
result = new FasterPaymentsAccountPayload(protoEntry.getPaymentMethodId(), protoEntry.getId(),
protoEntry.getMaxTradePeriod(), protoEntry.getFasterPaymentsAccountPayload().getSortCode(),
protoEntry.getFasterPaymentsAccountPayload().getAccountNr());
result = new FasterPaymentsAccountPayload(proto.getPaymentMethodId(), proto.getId(),
proto.getMaxTradePeriod(), proto.getFasterPaymentsAccountPayload().getSortCode(),
proto.getFasterPaymentsAccountPayload().getAccountNr());
break;
case INTERAC_E_TRANSFER_ACCOUNT_PAYLOAD:
PB.InteracETransferAccountPayload interacETransferAccountPayload =
protoEntry.getInteracETransferAccountPayload();
result = new InteracETransferAccountPayload(protoEntry.getPaymentMethodId(), protoEntry.getId(),
protoEntry.getMaxTradePeriod(), interacETransferAccountPayload.getEmail(),
proto.getInteracETransferAccountPayload();
result = new InteracETransferAccountPayload(proto.getPaymentMethodId(), proto.getId(),
proto.getMaxTradePeriod(), interacETransferAccountPayload.getEmail(),
interacETransferAccountPayload.getHolderName(),
interacETransferAccountPayload.getQuestion(),
interacETransferAccountPayload.getAnswer());
break;
case O_K_PAY_ACCOUNT_PAYLOAD:
result = getOkPayAccountPayload(protoEntry);
result = getOkPayAccountPayload(proto);
break;
case PERFECT_MONEY_ACCOUNT_PAYLOAD:
result = new PerfectMoneyAccountPayload(protoEntry.getPaymentMethodId(), protoEntry.getId(),
protoEntry.getMaxTradePeriod(), protoEntry.getPerfectMoneyAccountPayload().getAccountNr());
result = new PerfectMoneyAccountPayload(proto.getPaymentMethodId(), proto.getId(),
proto.getMaxTradePeriod(), proto.getPerfectMoneyAccountPayload().getAccountNr());
break;
case SWISH_ACCOUNT_PAYLOAD:
result = new SwishAccountPayload(protoEntry.getPaymentMethodId(), protoEntry.getId(),
protoEntry.getMaxTradePeriod(), protoEntry.getSwishAccountPayload().getMobileNr(),
protoEntry.getSwishAccountPayload().getHolderName());
result = new SwishAccountPayload(proto.getPaymentMethodId(), proto.getId(),
proto.getMaxTradePeriod(), proto.getSwishAccountPayload().getMobileNr(),
proto.getSwishAccountPayload().getHolderName());
break;
case U_S_POSTAL_MONEY_ORDER_ACCOUNT_PAYLOAD:
result = new USPostalMoneyOrderAccountPayload(protoEntry.getPaymentMethodId(), protoEntry.getId(),
protoEntry.getMaxTradePeriod(), protoEntry.getUSPostalMoneyOrderAccountPayload().getPostalAddress(),
protoEntry.getUSPostalMoneyOrderAccountPayload().getHolderName());
result = new USPostalMoneyOrderAccountPayload(proto.getPaymentMethodId(), proto.getId(),
proto.getMaxTradePeriod(), proto.getUSPostalMoneyOrderAccountPayload().getPostalAddress(),
proto.getUSPostalMoneyOrderAccountPayload().getHolderName());
break;
default:
log.error("Unknown paymentaccountcontractdata:{}", protoEntry.getMessageCase());
log.error("Unknown paymentaccountcontractdata:{}", proto.getMessageCase());
}
return result;
}

View file

@ -27,7 +27,6 @@ import lombok.extern.slf4j.Slf4j;
import org.bitcoinj.core.Coin;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@ -35,11 +34,16 @@ import java.util.Optional;
// Don't use Enum as it breaks serialisation when changing entries and we want to stay flexible here
@EqualsAndHashCode
@EqualsAndHashCode(exclude = {"maxTradePeriod", "maxTradeLimit"})
@Getter
@ToString
@Slf4j
public final class PaymentMethod implements PersistablePayload, Comparable {
///////////////////////////////////////////////////////////////////////////////////////////
// Static
///////////////////////////////////////////////////////////////////////////////////////////
// time in blocks (average 10 min for one block confirmation
private static final long HOUR = 3600_000;
private static final long DAY = HOUR * 24;
@ -111,10 +115,20 @@ public final class PaymentMethod implements PersistablePayload, Comparable {
BLOCK_CHAINS = new PaymentMethod(BLOCK_CHAINS_ID, DAY, Coin.parseCoin("1"))
));
///////////////////////////////////////////////////////////////////////////////////////////
// Instance fields
///////////////////////////////////////////////////////////////////////////////////////////
private final String id;
private long maxTradePeriod;
private long maxTradeLimit;
///////////////////////////////////////////////////////////////////////////////////////////
// Constructor
///////////////////////////////////////////////////////////////////////////////////////////
/**
* @param id against charge back risk. If Bank do the charge back quickly the Arbitrator and the seller can push another
* double spend tx to invalidate the time locked payout tx. For the moment we set all to 0 but will have it in
@ -128,30 +142,41 @@ public final class PaymentMethod implements PersistablePayload, Comparable {
this.maxTradeLimit = maxTradeLimit.value;
}
///////////////////////////////////////////////////////////////////////////////////////////
// PROTO BUFFER
///////////////////////////////////////////////////////////////////////////////////////////
@Override
public PB.PaymentMethod toProtoMessage() {
return PB.PaymentMethod.newBuilder()
.setId(id)
.setMaxTradePeriod(maxTradePeriod)
.setMaxTradeLimit(maxTradeLimit).build();
}
public static PaymentMethod fromProto(PB.PaymentMethod proto) {
return new PaymentMethod(proto.getId(),
proto.getMaxTradePeriod(),
Coin.valueOf(proto.getMaxTradeLimit()));
}
///////////////////////////////////////////////////////////////////////////////////////////
// API
///////////////////////////////////////////////////////////////////////////////////////////
// Used for dummy entries in payment methods list (SHOW_ALL)
public PaymentMethod(String id) {
this(id, 0, Coin.ZERO);
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
try {
in.defaultReadObject();
// In case we update those values we want that the persisted accounts get updated as well
PaymentMethod paymentMethod = PaymentMethod.getPaymentMethodById(id);
this.maxTradePeriod = paymentMethod.getMaxTradePeriod();
this.maxTradeLimit = paymentMethod.getMaxTradeLimit();
} catch (Throwable t) {
log.warn("Cannot be deserialized." + t.getMessage());
}
}
public static PaymentMethod getPaymentMethodById(String id) {
Optional<PaymentMethod> paymentMethodOptional = ALL_VALUES.stream().filter(e -> e.getId().equals(id)).findFirst();
if (paymentMethodOptional.isPresent())
return paymentMethodOptional.get();
else
return new PaymentMethod(Res.get("shared.na"), DAY, Coin.parseCoin("0"));
return new PaymentMethod(Res.get("shared.na"));
}
public Coin getMaxTradeLimitAsCoin() {
@ -165,17 +190,4 @@ public final class PaymentMethod implements PersistablePayload, Comparable {
else
return 0;
}
@Override
public PB.PaymentMethod toProtoMessage() {
return PB.PaymentMethod.newBuilder()
.setId(id)
.setMaxTradePeriod(maxTradePeriod)
.setMaxTradeLimit(maxTradeLimit).build();
}
public static PaymentMethod fromProto(PB.PaymentMethod paymentMethod) {
return new PaymentMethod(paymentMethod.getId(), paymentMethod.getMaxTradePeriod(),
Coin.valueOf(paymentMethod.getMaxTradeLimit()));
}
}

View file

@ -18,17 +18,12 @@
package io.bisq.core.proto;
import io.bisq.common.locale.CurrencyUtil;
import io.bisq.core.filter.PaymentAccountFilter;
import io.bisq.core.payment.payload.BankAccountPayload;
import io.bisq.core.payment.payload.CountryBasedPaymentAccountPayload;
import io.bisq.generated.protobuffer.PB;
public class ProtoUtil {
public class ProtoCoreUtil {
public static PaymentAccountFilter getPaymentAccountFilter(PB.PaymentAccountFilter accountFilter) {
return new PaymentAccountFilter(accountFilter.getPaymentMethodId(), accountFilter.getGetMethodName(),
accountFilter.getValue());
}
public static String getCurrencyCode(PB.OfferPayload pbOffer) {
return CurrencyUtil.isCryptoCurrency(pbOffer.getBaseCurrencyCode()) ? pbOffer.getBaseCurrencyCode() : pbOffer.getCounterCurrencyCode();

View file

@ -150,7 +150,7 @@ public class CoreNetworkProtoResolver implements NetworkProtoResolver {
case TRADE_STATISTICS:
return TradeStatistics.fromProto(proto.getTradeStatistics());
case MAILBOX_STORAGE_PAYLOAD:
return MailboxStoragePayload.fromProto(proto.getMailboxStoragePayload(), this);
return MailboxStoragePayload.fromProto(proto.getMailboxStoragePayload());
case OFFER_PAYLOAD:
return OfferPayload.fromProto(proto.getOfferPayload());
default:

View file

@ -176,16 +176,16 @@ public class ProcessModel implements Model, PersistablePayload {
public boolean isPeersPaymentAccountDataAreBanned(PaymentAccountPayload paymentAccountPayload,
PaymentAccountFilter[] appliedPaymentAccountFilter) {
return filterManager.getFilter() != null &&
filterManager.getFilter().bannedPaymentAccounts.stream()
filterManager.getFilter().getBannedPaymentAccounts().stream()
.filter(paymentAccountFilter -> {
final boolean samePaymentMethodId = paymentAccountFilter.paymentMethodId.equals(
final boolean samePaymentMethodId = paymentAccountFilter.getPaymentMethodId().equals(
paymentAccountPayload.getPaymentMethodId());
if (samePaymentMethodId) {
try {
Method method = paymentAccountPayload.getClass().getMethod(paymentAccountFilter.getMethodName);
Method method = paymentAccountPayload.getClass().getMethod(paymentAccountFilter.getGetMethodName());
String result = (String) method.invoke(paymentAccountPayload);
appliedPaymentAccountFilter[0] = paymentAccountFilter;
return result.equals(paymentAccountFilter.value);
return result.equals(paymentAccountFilter.getValue());
} catch (Throwable e) {
log.error(e.getMessage());
return false;

View file

@ -11,8 +11,8 @@ import io.bisq.core.offer.OfferPayload;
import io.bisq.generated.protobuffer.PB;
import io.bisq.network.p2p.storage.payload.LazyProcessedStoragePayload;
import io.bisq.network.p2p.storage.payload.PersistedStoragePayload;
import lombok.Getter;
import lombok.ToString;
import lombok.EqualsAndHashCode;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import org.bitcoinj.core.Coin;
import org.bitcoinj.utils.ExchangeRate;
@ -20,46 +20,44 @@ import org.bitcoinj.utils.Fiat;
import org.springframework.util.CollectionUtils;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import java.security.PublicKey;
import java.util.Date;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
@ToString
@Slf4j
@Immutable
public final class TradeStatistics implements LazyProcessedStoragePayload, /*CapabilityRequiringPayload,*/ PersistedStoragePayload {
@JsonExclude
public static final long TTL = TimeUnit.DAYS.toMillis(30);
// We don't include the pubKeyRing as both traders might publish it if the maker uses an old
// version and update later (taker publishes first, then later maker)
// We also don't include the trade date as that is set locally and different for maker and taker
// Payload
public final String baseCurrency;
public final String counterCurrency;
public final OfferPayload.Direction direction;
public final long tradePrice;
public final long tradeAmount;
public final long tradeDate;
public final String paymentMethodId;
public final long offerDate;
public final boolean useMarketBasedPrice;
public final double marketPriceMargin;
public final long offerAmount;
public final long offerMinAmount;
@Getter
public final String offerId;
public final String depositTxId;
@Slf4j
@EqualsAndHashCode(exclude = {"pubKeyRing"})
@Value
public final class TradeStatistics implements LazyProcessedStoragePayload, PersistedStoragePayload /*,CapabilityRequiringPayload*/ {
@JsonExclude
public final PubKeyRing pubKeyRing;
private final long TTL = TimeUnit.DAYS.toMillis(30);
private final OfferPayload.Direction direction;
private final String baseCurrency;
private final String counterCurrency;
private final String offerPaymentMethod;
private final long offerDate;
private final boolean offerUseMarketBasedPrice;
private final double offerMarketPriceMargin;
private final long offerAmount;
private final long offerMinAmount;
private final String offerId;
private final long tradePrice;
private final long tradeAmount;
private final long tradeDate;
private final String depositTxId;
@JsonExclude
private final PubKeyRing pubKeyRing;
// Should be only used in emergency case if we need to add data but do not want to break backward compatibility
// at the P2P network storage checks. The hash of the object will be used to verify if the data is valid. Any new
// field in a class would break that hash and therefore break the storage mechanism.
@Getter
@Nullable
private Map<String, String> extraDataMap;
// Called from domain
public TradeStatistics(OfferPayload offerPayload,
Price tradePrice,
Coin tradeAmount,
@ -90,28 +88,28 @@ public final class TradeStatistics implements LazyProcessedStoragePayload, /*Cap
///////////////////////////////////////////////////////////////////////////////////////////
private TradeStatistics(OfferPayload.Direction direction,
String baseCurrency,
String counterCurrency,
String offerPaymentMethod,
long offerDate,
boolean offerUseMarketBasedPrice,
double offerMarketPriceMargin,
long offerAmount,
long offerMinAmount,
String offerId,
long tradePrice,
long tradeAmount,
long tradeDate,
String depositTxId,
PubKeyRing pubKeyRing,
@Nullable Map<String, String> extraDataMap) {
String baseCurrency,
String counterCurrency,
String offerPaymentMethod,
long offerDate,
boolean offerUseMarketBasedPrice,
double offerMarketPriceMargin,
long offerAmount,
long offerMinAmount,
String offerId,
long tradePrice,
long tradeAmount,
long tradeDate,
String depositTxId,
PubKeyRing pubKeyRing,
@Nullable Map<String, String> extraDataMap) {
this.direction = direction;
this.baseCurrency = baseCurrency;
this.counterCurrency = counterCurrency;
this.paymentMethodId = offerPaymentMethod;
this.offerPaymentMethod = offerPaymentMethod;
this.offerDate = offerDate;
this.useMarketBasedPrice = offerUseMarketBasedPrice;
this.marketPriceMargin = offerMarketPriceMargin;
this.offerUseMarketBasedPrice = offerUseMarketBasedPrice;
this.offerMarketPriceMargin = offerMarketPriceMargin;
this.offerAmount = offerAmount;
this.offerMinAmount = offerMinAmount;
this.offerId = offerId;
@ -126,44 +124,43 @@ public final class TradeStatistics implements LazyProcessedStoragePayload, /*Cap
@Override
public PB.StoragePayload toProtoMessage() {
final PB.TradeStatistics.Builder builder = PB.TradeStatistics.newBuilder()
.setDirection(OfferPayload.Direction.toProtoMessage(direction))
.setBaseCurrency(baseCurrency)
.setCounterCurrency(counterCurrency)
.setDirection(PB.OfferPayload.Direction.valueOf(direction.name()))
.setTradePrice(tradePrice)
.setTradeAmount(tradeAmount)
.setTradeDate(tradeDate)
.setPaymentMethodId(paymentMethodId)
.setPaymentMethodId(offerPaymentMethod)
.setOfferDate(offerDate)
.setUseMarketBasedPrice(useMarketBasedPrice)
.setMarketPriceMargin(marketPriceMargin)
.setOfferUseMarketBasedPrice(offerUseMarketBasedPrice)
.setOfferMarketPriceMargin(offerMarketPriceMargin)
.setOfferAmount(offerAmount)
.setOfferMinAmount(offerMinAmount)
.setOfferId(offerId)
.setTradePrice(tradePrice)
.setTradeAmount(tradeAmount)
.setTradeDate(tradeDate)
.setDepositTxId(depositTxId)
.setPubKeyRing(pubKeyRing.toProtoMessage());
Optional.ofNullable(extraDataMap).ifPresent(builder::putAllExtraDataMap);
Optional.ofNullable(extraDataMap).ifPresent(builder::putAllExtraData);
return PB.StoragePayload.newBuilder().setTradeStatistics(builder).build();
}
public static TradeStatistics fromProto(PB.TradeStatistics tradeStatistics) {
public static TradeStatistics fromProto(PB.TradeStatistics proto) {
return new TradeStatistics(
OfferPayload.Direction.fromProto(tradeStatistics.getDirection()),
tradeStatistics.getBaseCurrency(),
tradeStatistics.getCounterCurrency(),
tradeStatistics.getPaymentMethodId(),
tradeStatistics.getOfferDate(),
tradeStatistics.getUseMarketBasedPrice(),
tradeStatistics.getMarketPriceMargin(),
tradeStatistics.getOfferAmount(),
tradeStatistics.getOfferMinAmount(),
tradeStatistics.getOfferId(),
tradeStatistics.getTradePrice(),
tradeStatistics.getTradeAmount(),
tradeStatistics.getTradeDate(),
tradeStatistics.getDepositTxId(),
PubKeyRing.fromProto(tradeStatistics.getPubKeyRing()),
CollectionUtils.isEmpty(tradeStatistics.getExtraDataMapMap()) ?
null : tradeStatistics.getExtraDataMapMap());
OfferPayload.Direction.fromProto(proto.getDirection()),
proto.getBaseCurrency(),
proto.getCounterCurrency(),
proto.getPaymentMethodId(),
proto.getOfferDate(),
proto.getOfferUseMarketBasedPrice(),
proto.getOfferMarketPriceMargin(),
proto.getOfferAmount(),
proto.getOfferMinAmount(),
proto.getOfferId(),
proto.getTradePrice(),
proto.getTradeAmount(),
proto.getTradeDate(),
proto.getDepositTxId(),
PubKeyRing.fromProto(proto.getPubKeyRing()),
CollectionUtils.isEmpty(proto.getExtraDataMap()) ? null : proto.getExtraDataMap());
}
@ -171,11 +168,6 @@ public final class TradeStatistics implements LazyProcessedStoragePayload, /*Cap
// Getters
///////////////////////////////////////////////////////////////////////////////////////////
@Override
public long getTTL() {
return TTL;
}
@Override
public PublicKey getOwnerPubKey() {
return pubKeyRing.getSignaturePubKey();
@ -211,55 +203,4 @@ public final class TradeStatistics implements LazyProcessedStoragePayload, /*Cap
else
return new Volume(new ExchangeRate((Fiat) getTradePrice().getMonetary()).coinToFiat(getTradeAmount()));
}
// We don't include the pubKeyRing as both traders might publish it if the maker uses an old
// version and update later (taker publishes first, then later maker)
// We also don't include the trade date as that is set locally and different for maker and taker
@Override
public int hashCode() {
int result;
long temp;
result = baseCurrency != null ? baseCurrency.hashCode() : 0;
result = 31 * result + (counterCurrency != null ? counterCurrency.hashCode() : 0);
result = 31 * result + (direction != null ? direction.hashCode() : 0);
result = 31 * result + (int) (tradePrice ^ (tradePrice >>> 32));
result = 31 * result + (int) (tradeAmount ^ (tradeAmount >>> 32));
result = 31 * result + (paymentMethodId != null ? paymentMethodId.hashCode() : 0);
result = 31 * result + (int) (offerDate ^ (offerDate >>> 32));
result = 31 * result + (useMarketBasedPrice ? 1 : 0);
temp = Double.doubleToLongBits(marketPriceMargin);
result = 31 * result + (int) (temp ^ (temp >>> 32));
result = 31 * result + (int) (offerAmount ^ (offerAmount >>> 32));
result = 31 * result + (int) (offerMinAmount ^ (offerMinAmount >>> 32));
result = 31 * result + (offerId != null ? offerId.hashCode() : 0);
result = 31 * result + (depositTxId != null ? depositTxId.hashCode() : 0);
result = 31 * result + (extraDataMap != null ? extraDataMap.hashCode() : 0);
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TradeStatistics that = (TradeStatistics) o;
if (tradePrice != that.tradePrice) return false;
if (tradeAmount != that.tradeAmount) return false;
if (offerDate != that.offerDate) return false;
if (useMarketBasedPrice != that.useMarketBasedPrice) return false;
if (Double.compare(that.marketPriceMargin, marketPriceMargin) != 0) return false;
if (offerAmount != that.offerAmount) return false;
if (offerMinAmount != that.offerMinAmount) return false;
if (baseCurrency != null ? !baseCurrency.equals(that.baseCurrency) : that.baseCurrency != null) return false;
if (counterCurrency != null ? !counterCurrency.equals(that.counterCurrency) : that.counterCurrency != null)
return false;
if (direction != that.direction) return false;
if (paymentMethodId != null ? !paymentMethodId.equals(that.paymentMethodId) : that.paymentMethodId != null)
return false;
if (offerId != null ? !offerId.equals(that.offerId) : that.offerId != null) return false;
if (depositTxId != null ? !depositTxId.equals(that.depositTxId) : that.depositTxId != null) return false;
return !(extraDataMap != null ? !extraDataMap.equals(that.extraDataMap) : that.extraDataMap != null);
}
}

View file

@ -5,15 +5,18 @@ import io.bisq.common.monetary.Price;
import io.bisq.common.monetary.Volume;
import io.bisq.common.util.MathUtils;
import io.bisq.core.offer.OfferPayload;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.bitcoinj.core.Coin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.concurrent.Immutable;
@Immutable
@EqualsAndHashCode
@ToString
@Slf4j
public final class TradeStatisticsForJson {
private static final Logger log = LoggerFactory.getLogger(TradeStatisticsForJson.class);
public final String currency;
public final OfferPayload.Direction direction;
@ -37,21 +40,20 @@ public final class TradeStatisticsForJson {
public long primaryMarketTradeAmount;
public long primaryMarketTradeVolume;
public TradeStatisticsForJson(TradeStatistics tradeStatistics) {
this.direction = OfferPayload.Direction.valueOf(tradeStatistics.direction.name());
this.direction = OfferPayload.Direction.valueOf(tradeStatistics.getDirection().name());
this.currency = tradeStatistics.getCurrencyCode();
this.paymentMethod = tradeStatistics.paymentMethodId;
this.offerDate = tradeStatistics.offerDate;
this.useMarketBasedPrice = tradeStatistics.useMarketBasedPrice;
this.marketPriceMargin = tradeStatistics.marketPriceMargin;
this.offerAmount = tradeStatistics.offerAmount;
this.offerMinAmount = tradeStatistics.offerMinAmount;
this.paymentMethod = tradeStatistics.getOfferPaymentMethod();
this.offerDate = tradeStatistics.getOfferDate();
this.useMarketBasedPrice = tradeStatistics.isOfferUseMarketBasedPrice();
this.marketPriceMargin = tradeStatistics.getOfferMarketPriceMargin();
this.offerAmount = tradeStatistics.getOfferAmount();
this.offerMinAmount = tradeStatistics.getOfferMinAmount();
this.offerId = tradeStatistics.getOfferId();
this.tradePrice = tradeStatistics.tradePrice;
this.tradeAmount = tradeStatistics.tradeAmount;
this.tradeDate = tradeStatistics.tradeDate;
this.depositTxId = tradeStatistics.depositTxId;
this.tradePrice = tradeStatistics.getTradePrice().getValue();
this.tradeAmount = tradeStatistics.getTradeAmount().getValue();
this.tradeDate = tradeStatistics.getTradeDate().getTime();
this.depositTxId = tradeStatistics.getDepositTxId();
try {
@ -77,12 +79,11 @@ public final class TradeStatisticsForJson {
(long) MathUtils.scaleUpByPowerOf10(getTradeVolume().getValue(), 4) : 0;
}
} catch (Throwable t) {
log.error("Error at setDisplayStrings: " + t.getMessage());
log.error(t.getMessage());
t.printStackTrace();
}
}
public Price getTradePrice() {
return Price.valueOf(currency, tradePrice);
}
@ -94,75 +95,4 @@ public final class TradeStatisticsForJson {
public Volume getTradeVolume() {
return getTradePrice().getVolumeByAmount(getTradeAmount());
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof TradeStatisticsForJson)) return false;
TradeStatisticsForJson that = (TradeStatisticsForJson) o;
if (tradePrice != that.tradePrice) return false;
if (tradeAmount != that.tradeAmount) return false;
if (tradeDate != that.tradeDate) return false;
if (offerDate != that.offerDate) return false;
if (useMarketBasedPrice != that.useMarketBasedPrice) return false;
if (Double.compare(that.marketPriceMargin, marketPriceMargin) != 0) return false;
if (offerAmount != that.offerAmount) return false;
if (offerMinAmount != that.offerMinAmount) return false;
if (currency != null ? !currency.equals(that.currency) : that.currency != null) return false;
if (direction != that.direction) return false;
if (paymentMethod != null ? !paymentMethod.equals(that.paymentMethod) : that.paymentMethod != null)
return false;
if (offerId != null ? !offerId.equals(that.offerId) : that.offerId != null) return false;
return !(depositTxId != null ? !depositTxId.equals(that.depositTxId) : that.depositTxId != null);
}
@Override
public int hashCode() {
int result;
long temp;
result = currency != null ? currency.hashCode() : 0;
result = 31 * result + (direction != null ? direction.hashCode() : 0);
result = 31 * result + (int) (tradePrice ^ (tradePrice >>> 32));
result = 31 * result + (int) (tradeAmount ^ (tradeAmount >>> 32));
result = 31 * result + (int) (tradeDate ^ (tradeDate >>> 32));
result = 31 * result + (paymentMethod != null ? paymentMethod.hashCode() : 0);
result = 31 * result + (int) (offerDate ^ (offerDate >>> 32));
result = 31 * result + (useMarketBasedPrice ? 1 : 0);
temp = Double.doubleToLongBits(marketPriceMargin);
result = 31 * result + (int) (temp ^ (temp >>> 32));
result = 31 * result + (int) (offerAmount ^ (offerAmount >>> 32));
result = 31 * result + (int) (offerMinAmount ^ (offerMinAmount >>> 32));
result = 31 * result + (offerId != null ? offerId.hashCode() : 0);
result = 31 * result + (depositTxId != null ? depositTxId.hashCode() : 0);
result = 31 * result + (currencyPair != null ? currencyPair.hashCode() : 0);
result = 31 * result + (primaryMarketDirection != null ? primaryMarketDirection.hashCode() : 0);
result = 31 * result + (int) (primaryMarketTradePrice ^ (primaryMarketTradePrice >>> 32));
result = 31 * result + (int) (primaryMarketTradeAmount ^ (primaryMarketTradeAmount >>> 32));
result = 31 * result + (int) (primaryMarketTradeVolume ^ (primaryMarketTradeVolume >>> 32));
return result;
}
@Override
public String toString() {
return "TradeStatisticsForJson{" +
"currency='" + currency + '\'' +
", direction=" + direction +
", tradePrice=" + tradePrice +
", tradeAmount=" + tradeAmount +
", tradeDate=" + tradeDate +
", paymentMethod='" + paymentMethod + '\'' +
", offerDate=" + offerDate +
", useMarketBasedPrice=" + useMarketBasedPrice +
", marketPriceMargin=" + marketPriceMargin +
", offerAmount=" + offerAmount +
", offerMinAmount=" + offerMinAmount +
", offerId='" + offerId + '\'' +
", depositTxId='" + depositTxId + '\'' +
", currencyPair='" + currencyPair + '\'' +
", primaryMarketTradeAmount=" + primaryMarketTradeAmount +
", primaryMarketTradeVolume=" + primaryMarketTradeVolume +
'}';
}
}

View file

@ -85,20 +85,18 @@ public class UserPayload implements PersistableEnvelope {
return PB.PersistableEnvelope.newBuilder().setUserPayload(builder).build();
}
public static UserPayload fromProto(PB.UserPayload user) {
Set<PaymentAccount> collect = user.getPaymentAccountsList().stream().map(paymentAccount -> PaymentAccount.fromProto(paymentAccount)).collect(Collectors.toSet());
UserPayload vo = new UserPayload(user.getAccountId(),
collect,
user.hasCurrentPaymentAccount() ? PaymentAccount.fromProto(user.getCurrentPaymentAccount()) : null,
user.getAcceptedLanguageLocaleCodesList(),
user.hasDevelopersAlert() ? Alert.fromProto(user.getDevelopersAlert()) : null,
user.hasDisplayedAlert() ? Alert.fromProto(user.getDisplayedAlert()) : null,
user.hasDevelopersFilter() ? Filter.fromProto(user.getDevelopersFilter()) : null,
user.hasRegisteredArbitrator() ? Arbitrator.fromProto(user.getRegisteredArbitrator()) : null,
user.hasRegisteredMediator() ? Mediator.fromProto(user.getRegisteredMediator()) : null,
user.getAcceptedArbitratorsList().stream().map(Arbitrator::fromProto).collect(Collectors.toList()),
user.getAcceptedMediatorsList().stream().map(Mediator::fromProto).collect(Collectors.toList())
public static UserPayload fromProto(PB.UserPayload proto) {
return new UserPayload(proto.getAccountId(),
proto.getPaymentAccountsList().stream().map(PaymentAccount::fromProto).collect(Collectors.toSet()),
proto.hasCurrentPaymentAccount() ? PaymentAccount.fromProto(proto.getCurrentPaymentAccount()) : null,
proto.getAcceptedLanguageLocaleCodesList(),
proto.hasDevelopersAlert() ? Alert.fromProto(proto.getDevelopersAlert()) : null,
proto.hasDisplayedAlert() ? Alert.fromProto(proto.getDisplayedAlert()) : null,
proto.hasDevelopersFilter() ? Filter.fromProto(proto.getDevelopersFilter()) : null,
proto.hasRegisteredArbitrator() ? Arbitrator.fromProto(proto.getRegisteredArbitrator()) : null,
proto.hasRegisteredMediator() ? Mediator.fromProto(proto.getRegisteredMediator()) : null,
proto.getAcceptedArbitratorsList().stream().map(Arbitrator::fromProto).collect(Collectors.toList()),
proto.getAcceptedMediatorsList().stream().map(Mediator::fromProto).collect(Collectors.toList())
);
return vo;
}
}

View file

@ -43,7 +43,7 @@ public class ArbitratorTest {
new Date(),
getBytes(100),
"registrationSignature",
"string", null);
null, null, null);
}
// TODO move to common if used often

View file

@ -157,6 +157,7 @@ class ArbitratorRegistrationViewModel extends ActivatableViewModel {
registrationKey.getPubKey(),
registrationSignature,
emailAddress,
null,
null
);

View file

@ -63,7 +63,7 @@ public class ParameterViewItem {
}
public static boolean contains(VoteItem selectedItem) {
return instances.stream().filter(e -> e.voteItem.votingType == selectedItem.votingType).findAny().isPresent();
return instances.stream().filter(e -> e.voteItem.getVotingType() == selectedItem.getVotingType()).findAny().isPresent();
}
public static boolean isEmpty() {
@ -72,12 +72,12 @@ public class ParameterViewItem {
private ParameterViewItem(VoteItem voteItem, VBox vBox, DoubleProperty labelWidth, VotingDefaultValues votingDefaultValues, Runnable removeHandler) {
this.voteItem = voteItem;
originalValue = votingDefaultValues.getValueByVotingType(voteItem.votingType);
originalValue = votingDefaultValues.getValueByVotingType(voteItem.getVotingType());
HBox hBox = new HBox();
hBox.setSpacing(5);
vBox.getChildren().add(hBox);
label = new Label(voteItem.name + ":");
label = new Label(voteItem.getName() + ":");
HBox.setMargin(label, new Insets(4, 0, 0, 0));
numberChangeListener = (observable, oldValue, newValue) -> {
if ((double) newValue > 0) {

View file

@ -141,7 +141,7 @@ public class VoteView extends ActivatableView<GridPane, Void> {
parametersComboBox.setConverter(new StringConverter<VoteItem>() {
@Override
public String toString(VoteItem item) {
return item.name;
return item.getName();
}
@Override

View file

@ -648,12 +648,12 @@ public class TradesChartsView extends ActivatableViewAndModel<VBox, TradesCharts
@NotNull
private String getDirectionLabel(TradeStatistics item) {
return formatter.getDirectionWithCode(OfferPayload.Direction.valueOf(item.direction.name()), item.getCurrencyCode());
return formatter.getDirectionWithCode(OfferPayload.Direction.valueOf(item.getDirection().name()), item.getCurrencyCode());
}
@NotNull
private String getPaymentMethodLabel(TradeStatistics item) {
return Res.get(item.paymentMethodId);
return Res.get(item.getOfferPaymentMethod());
}
private void layout() {

View file

@ -248,7 +248,7 @@ class TradesChartsViewModel extends ActivatableViewModel {
final long dateAsTime = new Date().getTime();
tradeStatisticsByCurrency.stream().forEach(e -> {
Set<TradeStatistics> set;
final long time = getTickFromTime(e.tradeDate, tickUnit);
final long time = getTickFromTime(e.getTradeDate().getTime(), tickUnit);
final long now = getTickFromTime(dateAsTime, tickUnit);
long index = maxTicks - (now - time);
if (itemsPerInterval.containsKey(index)) {
@ -289,7 +289,7 @@ class TradesChartsViewModel extends ActivatableViewModel {
long numTrades = set.size();
for (TradeStatistics item : set) {
long tradePriceAsLong = item.tradePrice;
long tradePriceAsLong = item.getTradePrice().getValue();
if (CurrencyUtil.isCryptoCurrency(getCurrencyCode())) {
low = (low != 0) ? Math.max(low, tradePriceAsLong) : tradePriceAsLong;
high = (high != 0) ? Math.min(high, tradePriceAsLong) : tradePriceAsLong;
@ -299,14 +299,14 @@ class TradesChartsViewModel extends ActivatableViewModel {
}
accumulatedVolume += (item.getTradeVolume() != null) ? item.getTradeVolume().getValue() : 0;
accumulatedAmount += item.tradeAmount;
accumulatedAmount += item.getTradeAmount().getValue();
}
List<TradeStatistics> list = new ArrayList<>(set);
list.sort((o1, o2) -> (o1.tradeDate < o2.tradeDate ? -1 : (o1.tradeDate == o2.tradeDate ? 0 : 1)));
list.sort((o1, o2) -> (o1.getTradeDate().getTime() < o2.getTradeDate().getTime() ? -1 : (o1.getTradeDate().getTime() == o2.getTradeDate().getTime() ? 0 : 1)));
if (list.size() > 0) {
open = list.get(0).tradePrice;
close = list.get(list.size() - 1).tradePrice;
open = list.get(0).getTradePrice().getValue();
close = list.get(list.size() - 1).getTradePrice().getValue();
}
long averagePrice;

View file

@ -451,7 +451,7 @@ class OfferBookViewModel extends ActivatableViewModel {
boolean isOfferBanned(Offer offer) {
return filterManager.getFilter() != null &&
filterManager.getFilter().bannedOfferIds.stream()
filterManager.getFilter().getBannedOfferIds().stream()
.filter(e -> e.equals(offer.getId()))
.findAny()
.isPresent();
@ -459,7 +459,7 @@ class OfferBookViewModel extends ActivatableViewModel {
boolean isNodeBanned(Offer offer) {
return filterManager.getFilter() != null &&
filterManager.getFilter().bannedNodeAddress.stream()
filterManager.getFilter().getBannedNodeAddress().stream()
.filter(e -> e.equals(offer.getMakerNodeAddress().getHostNameWithoutPostFix()))
.findAny()
.isPresent();

View file

@ -119,17 +119,17 @@ public class FilterWindow extends Overlay<FilterWindow> {
final Filter filter = filterManager.getDevelopersFilter();
if (filter != null) {
offerIdsInputTextField.setText(filter.bannedOfferIds.stream().collect(Collectors.joining(", ")));
nodesInputTextField.setText(filter.bannedNodeAddress.stream().collect(Collectors.joining(", ")));
if (filter.bannedPaymentAccounts != null) {
offerIdsInputTextField.setText(filter.getBannedOfferIds().stream().collect(Collectors.joining(", ")));
nodesInputTextField.setText(filter.getBannedNodeAddress().stream().collect(Collectors.joining(", ")));
if (filter.getBannedPaymentAccounts() != null) {
StringBuilder sb = new StringBuilder();
filter.bannedPaymentAccounts.stream().forEach(e -> {
if (e != null && e.paymentMethodId != null) {
sb.append(e.paymentMethodId)
filter.getBannedPaymentAccounts().stream().forEach(e -> {
if (e != null && e.getPaymentMethodId() != null) {
sb.append(e.getPaymentMethodId())
.append("|")
.append(e.getMethodName)
.append(e.getGetMethodName())
.append("|")
.append(e.value)
.append(e.getValue())
.append(", ");
}
});

View file

@ -1,7 +1,6 @@
package io.bisq.network.p2p;
import com.google.protobuf.ByteString;
import io.bisq.common.app.Version;
import io.bisq.common.crypto.SealedAndSigned;
import io.bisq.common.proto.network.NetworkEnvelope;
import io.bisq.generated.protobuffer.PB;
@ -11,7 +10,6 @@ import static com.google.common.base.Preconditions.checkNotNull;
@Value
public final class PrefixedSealedAndSignedMessage implements MailboxMessage, SendersNodeAddressMessage {
private final int messageVersion = Version.getP2PMessageVersion();
private final NodeAddress senderNodeAddress;
private final SealedAndSigned sealedAndSigned;
private final byte[] addressPrefixHash;
@ -21,7 +19,7 @@ public final class PrefixedSealedAndSignedMessage implements MailboxMessage, Sen
SealedAndSigned sealedAndSigned,
byte[] addressPrefixHash,
String uid) {
checkNotNull(senderNodeAddress, "senderNodeAddress must not be null at PrefixedSealedAndSignedMessage");
checkNotNull(senderNodeAddress, "senderNodeAddress must not be null");
this.senderNodeAddress = senderNodeAddress;
this.sealedAndSigned = sealedAndSigned;
this.addressPrefixHash = addressPrefixHash;
@ -32,10 +30,11 @@ public final class PrefixedSealedAndSignedMessage implements MailboxMessage, Sen
public PB.NetworkEnvelope toProtoNetworkEnvelope() {
return NetworkEnvelope.getDefaultBuilder().setPrefixedSealedAndSignedMessage(
PB.PrefixedSealedAndSignedMessage.newBuilder()
.setMessageVersion(messageVersion).setNodeAddress(senderNodeAddress.toProtoMessage())
.setNodeAddress(senderNodeAddress.toProtoMessage())
.setSealedAndSigned(sealedAndSigned.toProtoMessage())
.setAddressPrefixHash(ByteString.copyFrom(addressPrefixHash))
.setUid(uid)).build();
.setUid(uid))
.build();
}
public static PrefixedSealedAndSignedMessage fromProto(PB.PrefixedSealedAndSignedMessage proto) {

View file

@ -28,6 +28,7 @@ import io.bisq.network.p2p.storage.messages.*;
import io.bisq.network.p2p.storage.payload.*;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
@ -668,7 +669,7 @@ public class P2PDataStorage implements MessageListener, ConnectionListener {
Map<String, PB.ProtectedStorageEntry> protoResult =
map.entrySet().stream()
.collect(Collectors.toMap(
e -> e.getKey().toString(),
e -> e.getKey().toString(),
e -> (PB.ProtectedStorageEntry) e.getValue().toProtoMessage())
);
return PB.PersistableEnvelope.newBuilder().setPersistedEntryMap(PB.PersistedEntryMap.newBuilder().putAllPersistedEntryMap(protoResult)).build();
@ -731,8 +732,8 @@ public class P2PDataStorage implements MessageListener, ConnectionListener {
return PB.ByteArray.newBuilder().setBytes(ByteString.copyFrom(bytes)).build();
}
public static ByteArray fromProto(PB.ByteArray byteArray) {
return new ByteArray(byteArray.getBytes().toByteArray());
public static ByteArray fromProto(PB.ByteArray proto) {
return new ByteArray(proto.getBytes().toByteArray());
}
}
@ -740,6 +741,7 @@ public class P2PDataStorage implements MessageListener, ConnectionListener {
* Used as value in map
*/
@EqualsAndHashCode
@ToString
public static final class MapValue implements PersistablePayload {
// That object is saved to disc. We need to take care of changes to not break deserialization.
final public int sequenceNr;
@ -750,21 +752,13 @@ public class P2PDataStorage implements MessageListener, ConnectionListener {
this.timeStamp = timeStamp;
}
@Override
public String toString() {
return "MapValue{" +
"sequenceNr=" + sequenceNr +
", timeStamp=" + timeStamp +
'}';
}
@Override
public PB.MapValue toProtoMessage() {
return PB.MapValue.newBuilder().setSequenceNr(sequenceNr).setTimeStamp(timeStamp).build();
}
public static MapValue fromProto(PB.MapValue value) {
return new MapValue(value.getSequenceNr(), value.getTimeStamp());
public static MapValue fromProto(PB.MapValue proto) {
return new MapValue(proto.getSequenceNr(), proto.getTimeStamp());
}
}
}

View file

@ -24,7 +24,6 @@ import lombok.Setter;
import lombok.experimental.Delegate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
@ -44,8 +43,8 @@ public class SequenceNumberMap implements PersistableEnvelope {
public SequenceNumberMap() {
}
public SequenceNumberMap(SequenceNumberMap sequenceNumberMap) {
this.hashMap = sequenceNumberMap.getHashMap();
public SequenceNumberMap(SequenceNumberMap map) {
this.hashMap = map.getHashMap();
}
public SequenceNumberMap(HashMap<P2PDataStorage.ByteArray, P2PDataStorage.MapValue> hashMap) {
@ -57,25 +56,28 @@ public class SequenceNumberMap implements PersistableEnvelope {
return PB.PersistableEnvelope.newBuilder().setSequenceNumberMap(
PB.SequenceNumberMap.newBuilder().addAllSequenceNumberEntries(
hashMap.entrySet().stream()
.map(entry ->
PB.SequenceNumberEntry.newBuilder().setBytes(entry.getKey().toProtoMessage())
.setMapValue(entry.getValue().toProtoMessage()).build())
.collect(Collectors.toList()))).build();
.map(entry -> PB.SequenceNumberEntry.newBuilder()
.setBytes(entry.getKey().toProtoMessage())
.setMapValue(entry.getValue().toProtoMessage())
.build())
.collect(Collectors.toList())))
.build();
}
public static SequenceNumberMap fromProto(PB.SequenceNumberMap sequenceNumberMap) {
List<PB.SequenceNumberEntry> sequenceNumberEntryList = sequenceNumberMap.getSequenceNumberEntriesList();
HashMap<P2PDataStorage.ByteArray, P2PDataStorage.MapValue> result = new HashMap<>();
for (final PB.SequenceNumberEntry entry : sequenceNumberEntryList) {
result.put(P2PDataStorage.ByteArray.fromProto(entry.getBytes()), P2PDataStorage.MapValue.fromProto(entry.getMapValue()));
}
return new SequenceNumberMap(result);
public static SequenceNumberMap fromProto(PB.SequenceNumberMap proto) {
HashMap<P2PDataStorage.ByteArray, P2PDataStorage.MapValue> map = new HashMap<>();
proto.getSequenceNumberEntriesList().stream().forEach(entry -> {
map.put(P2PDataStorage.ByteArray.fromProto(entry.getBytes()), P2PDataStorage.MapValue.fromProto(entry.getMapValue()));
});
return new SequenceNumberMap(map);
}
// avoid warnings in IDE, because of type erasure intellij thinks there are duplicate methods generated by lombok delegate
private interface ExcludeFromDelegate<K,V> {
public void forEach(BiConsumer<? super P2PDataStorage.ByteArray, ? super P2PDataStorage.MapValue> action);
public void putAll(Map<? extends P2PDataStorage.ByteArray, ? extends P2PDataStorage.MapValue> all);
public void replaceAll(BiFunction<? super P2PDataStorage.ByteArray, ? super P2PDataStorage.MapValue, ? extends P2PDataStorage.MapValue> all);
private interface ExcludeFromDelegate<K, V> {
void forEach(BiConsumer<? super P2PDataStorage.ByteArray, ? super P2PDataStorage.MapValue> action);
void putAll(Map<? extends P2PDataStorage.ByteArray, ? extends P2PDataStorage.MapValue> all);
void replaceAll(BiFunction<? super P2PDataStorage.ByteArray, ? super P2PDataStorage.MapValue, ? extends P2PDataStorage.MapValue> all);
}
}

View file

@ -2,7 +2,6 @@ package io.bisq.network.p2p.storage.payload;
import com.google.protobuf.ByteString;
import io.bisq.common.crypto.Sig;
import io.bisq.common.proto.network.NetworkProtoResolver;
import io.bisq.generated.protobuffer.PB;
import io.bisq.network.p2p.PrefixedSealedAndSignedMessage;
import lombok.EqualsAndHashCode;
@ -29,7 +28,6 @@ import java.util.concurrent.TimeUnit;
@Slf4j
public final class MailboxStoragePayload implements StoragePayload {
private final long TTL = TimeUnit.DAYS.toMillis(10);
private final PrefixedSealedAndSignedMessage prefixedSealedAndSignedMessage;
private PublicKey senderPubKeyForAddOperation;
private final byte[] senderPubKeyForAddOperationBytes;
@ -50,13 +48,12 @@ public final class MailboxStoragePayload implements StoragePayload {
senderPubKeyForAddOperationBytes = Sig.getSigPublicKeyBytes(senderPubKeyForAddOperation);
ownerPubKeyBytes = Sig.getSigPublicKeyBytes(ownerPubKey);
this.extraDataMap = null;
}
public MailboxStoragePayload(PrefixedSealedAndSignedMessage prefixedSealedAndSignedMessage,
byte[] senderPubKeyForAddOperationBytes,
byte[] ownerPubKeyBytes,
@Nullable Map<String, String> extraDataMap) {
private MailboxStoragePayload(PrefixedSealedAndSignedMessage prefixedSealedAndSignedMessage,
byte[] senderPubKeyForAddOperationBytes,
byte[] ownerPubKeyBytes,
@Nullable Map<String, String> extraDataMap) {
this.prefixedSealedAndSignedMessage = prefixedSealedAndSignedMessage;
this.senderPubKeyForAddOperationBytes = senderPubKeyForAddOperationBytes;
this.ownerPubKeyBytes = ownerPubKeyBytes;
@ -72,17 +69,15 @@ public final class MailboxStoragePayload implements StoragePayload {
.setPrefixedSealedAndSignedMessage(prefixedSealedAndSignedMessage.toProtoNetworkEnvelope().getPrefixedSealedAndSignedMessage())
.setSenderPubKeyForAddOperationBytes(ByteString.copyFrom(senderPubKeyForAddOperationBytes))
.setOwnerPubKeyBytes(ByteString.copyFrom(ownerPubKeyBytes));
Optional.ofNullable(extraDataMap).ifPresent(builder::putAllExtraDataMap);
Optional.ofNullable(extraDataMap).ifPresent(builder::putAllExtraData);
return PB.StoragePayload.newBuilder().setMailboxStoragePayload(builder).build();
}
public static MailboxStoragePayload fromProto(PB.MailboxStoragePayload proto, NetworkProtoResolver networkProtoResolver) {
Map<String, String> extraDataMapMap = CollectionUtils.isEmpty(proto.getExtraDataMapMap()) ?
null : proto.getExtraDataMapMap();
public static MailboxStoragePayload fromProto(PB.MailboxStoragePayload proto) {
return new MailboxStoragePayload(
PrefixedSealedAndSignedMessage.fromProto(proto.getPrefixedSealedAndSignedMessage()),
proto.getSenderPubKeyForAddOperationBytes().toByteArray(),
proto.getOwnerPubKeyBytes().toByteArray(),
extraDataMapMap);
CollectionUtils.isEmpty(proto.getExtraDataMap()) ? null : proto.getExtraDataMap());
}
}

View file

@ -75,6 +75,7 @@ public class ProtectedStorageEntry implements NetworkPayload, PersistablePayload
proto.getSignature().toByteArray());
}
///////////////////////////////////////////////////////////////////////////////////////////
// API
///////////////////////////////////////////////////////////////////////////////////////////