all Messages and Payloads have been converted to proto, remaining task is implement all to/from proto methods

This commit is contained in:
Mike Rosseel 2017-02-03 07:56:37 +01:00
parent f327b03e18
commit 113e28f9ed
35 changed files with 980 additions and 210 deletions

View file

@ -53,16 +53,28 @@ public final class PubKeyRing implements Payload {
this.encryptionPubKeyBytes = new X509EncodedKeySpec(encryptionPubKey.getEncoded()).getEncoded();
}
public PubKeyRing(byte[] signaturePubKeyBytes, byte[] encryptionPubKeyBytes) {
this.signaturePubKeyBytes = signaturePubKeyBytes;
this.encryptionPubKeyBytes = encryptionPubKeyBytes;
init();
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
try {
in.defaultReadObject();
signaturePubKey = KeyFactory.getInstance(Sig.KEY_ALGO, "BC").generatePublic(new X509EncodedKeySpec(signaturePubKeyBytes));
encryptionPubKey = KeyFactory.getInstance(Encryption.ASYM_KEY_ALGO, "BC").generatePublic(new X509EncodedKeySpec(encryptionPubKeyBytes));
init();
} catch (Throwable t) {
log.warn("Cannot be deserialized." + t.getMessage());
}
}
private void init() {
try {
signaturePubKey = KeyFactory.getInstance(Sig.KEY_ALGO, "BC").generatePublic(new X509EncodedKeySpec(signaturePubKeyBytes));
encryptionPubKey = KeyFactory.getInstance(Encryption.ASYM_KEY_ALGO, "BC").generatePublic(new X509EncodedKeySpec(encryptionPubKeyBytes));
} catch (InvalidKeySpecException | NoSuchAlgorithmException | NoSuchProviderException e) {
e.printStackTrace();
log.error(e.getMessage());
} catch (Throwable t) {
log.warn("Cannot be deserialized." + t.getMessage());
}
}

View file

@ -24,7 +24,10 @@ import org.slf4j.LoggerFactory;
import java.io.IOException;
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.Arrays;
@ -47,15 +50,34 @@ public final class SealedAndSigned implements Payload {
this.sigPublicKeyBytes = new X509EncodedKeySpec(this.sigPublicKey.getEncoded()).getEncoded();
}
public SealedAndSigned(byte[] encryptedSecretKey, byte[] encryptedPayloadWithHmac, byte[] signature, byte[] sigPublicKeyBytes) {
this(encryptedSecretKey, encryptedPayloadWithHmac, signature, SealedAndSigned.createSigPublicKey(sigPublicKeyBytes));
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
try {
in.defaultReadObject();
sigPublicKey = KeyFactory.getInstance(Sig.KEY_ALGO, "BC").generatePublic(new X509EncodedKeySpec(sigPublicKeyBytes));
sigPublicKey = createSigPublicKey(sigPublicKeyBytes);
} catch (Throwable t) {
log.warn("Exception at readObject: " + t.getMessage());
}
}
/**
* We have the bytes, now recreate the sigPublicKey. This happens when receiving this class over the wire,
* because the public key is transient.
*/
static PublicKey createSigPublicKey(byte[] sigPublicKeyBytes) {
PublicKey publicKey = null;
try {
publicKey = KeyFactory.getInstance(Sig.KEY_ALGO, "BC")
.generatePublic(new X509EncodedKeySpec(sigPublicKeyBytes));
} catch (InvalidKeySpecException | NoSuchAlgorithmException | NoSuchProviderException e) {
log.error("Error creating sigPublicKey", e);
}
return publicKey;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;

View file

@ -19,9 +19,18 @@ message Envelope {
PreliminaryGetDataRequest preliminary_get_data_request = 6;
GetUpdatedDataRequest get_updated_data_request = 7;
GetPeersRequest get_peers_request = 8;
GetDataRequest get_data_request = 9;
GetDataResponse get_data_response = 10;
SendersNodeAddressMessage senders_node_address_message = 11;
GetPeersResponse get_peers_response = 9;
GetDataRequest get_data_request = 10;
GetDataResponse get_data_response = 11;
SendersNodeAddressMessage senders_node_address_message = 12;
PrefixedSealedAndSignedMessage prefixed_sealed_and_signed_message = 13;
OfferAvailabilityResponse offer_availability_response = 14;
RemoveDataMessage remove_data_message = 15;
AddDataMessage add_data_message = 16;
RemoveMailboxDataMessage remove_mailbox_data_message = 17;
DepositTxPublishedMessage deposit_tx_published_message = 18;
}
}
@ -34,12 +43,6 @@ message Pong {
int32 requestNonce = 1;
}
message RefreshTTLMessage {
bytes hash_of_data_and_seq_nr = 1; // 32 bytes
bytes signature = 2; // 46 bytes
bytes hash_of_payload = 3; // 32 bytes
int32 sequence_number = 4; // 4 bytes
}
message CloseConnectionMessage {
int64 message_version = 1;
@ -54,7 +57,7 @@ message PreliminaryGetDataRequest {
repeated int32 supported_capabilities = 4;
}
message GetUpdatedDataRequest {
message GetUpdatedDataRequest {
int64 message_version = 1;
NodeAddress sender_node_address = 2;
int32 nonce = 3;
@ -63,10 +66,18 @@ message GetUpdatedDataRequest {
// STOP GetDataRequest
message GetPeersRequest {
NodeAddress sender_node_address = 1;
int32 nonce = 2;
repeated int32 supported_capabilities = 3;
repeated Peer reported_peers = 4;
int32 message_version = 1;
NodeAddress sender_node_address = 2;
int32 nonce = 3;
repeated int32 supported_capabilities = 4;
repeated Peer reported_peers = 5;
}
message GetPeersResponse {
int32 message_version = 1;
int32 requestNonce = 2;
repeated Peer reportedPeers = 3;
repeated int32 supported_capabilities = 5;
}
message NodeAddress {
@ -86,28 +97,199 @@ message GetDataRequest {
message GetDataResponse {
int64 message_version = 1;
repeated int32 supported_capabilities = 2;
int32 request_nonce = 3;
bool is_get_updated_data_response = 4;
repeated ProtectedStorageEntry data_set = 5;
int32 request_nonce = 2;
bool is_get_updated_data_response = 3;
repeated ProtectedStorageEntry data_set = 4;
repeated int32 supported_capabilities = 5;
}
message ProtectedStorageEntry {
// private final byte[] ownerPubKeyBytes;
// public transient PublicKey ownerPubKey;
// public int sequenceNumber;
// public byte[] signature;
// @VisibleForTesting
// public long creationTimeStamp;
StoragePayload storagePayload = 1;
bytes owner_pub_key_bytes = 2;
int32 sequence_number = 3;
bytes signature = 4;
int64 creation_time_stamp = 5;
}
message SendersNodeAddressMessage {
oneof message {
Ping ping = 2;
GetUpdatedDataRequest get_updated_data_request = 1;
GetPeersRequest get_peers_request = 2;
PrefixedSealedAndSignedMessage prefixed_sealed_and_signed_message = 3;
}
}
// start BroadcastMessage
message BroadcastMessage {
oneof message {
RemoveDataMessage remove_data_message = 1;
AddDataMessage add_data_message = 2;
RefreshTTLMessage refresh_ttl_message = 3;
RemoveMailboxDataMessage remove_mailbox_data_message = 4;
}
}
message RemoveDataMessage {
ProtectedStorageEntry protected_storage_entry = 1;
}
message AddDataMessage {
ProtectedStorageEntry protected_storage_entry = 1;
}
message RefreshTTLMessage {
bytes hash_of_data_and_seq_nr = 1; // 32 bytes
bytes signature = 2; // 46 bytes
bytes hash_of_payload = 3; // 32 bytes
int32 sequence_number = 4; // 4 bytes
}
message RemoveMailboxDataMessage {
ProtectedStorageEntry protected_storage_entry = 1;
}
// end BroadcastMessage
// start storagepayloads
message StoragePayload {
//oneof message {
//}
}
message Alert {
int64 TTL = 1;
string message = 2;
string version = 3;
bool is_update_info = 4;
string signature_as_base64 = 5;
bytes storage_public_key_bytes = 6;
}
message Arbitrator {
int64 TTL = 1;
bytes btcPubKey = 2;
PubKeyRing pubKeyRing = 3;
NodeAddress arbitratorNodeAddress = 4;
repeated string languageCodes = 5;
string btcAddress = 6;
int64 registrationDate = 7;
string registrationSignature = 8;
bytes registrationPubKey = 9;
}
message Filter {
int64 TTL = 1;
repeated string bannedNodeAddress = 2;
repeated string bannedOfferIds = 3;
repeated PaymentAccountFilter bannedPaymentAccounts = 4;
string signatureAsBase64 = 5;
bytes publicKeyBytes = 6;
}
message PaymentAccountFilter {
string paymentMethodId = 1;
string getMethodName = 2;
string value = 3;
}
message CompensationRequestPayload {
int64 TTL = 1;
uint32 version = 2; // 1 byte
int64 creationDate = 3;
string uid = 4;
string name = 5;
string title = 6;
string category = 7;
string description = 8;
string link = 9;
int64 startDate = 10;
int64 endDate = 11;
int64 requestedBtc = 12;
string btcAddress = 13;
string nodeAddress = 14;
bytes p2pStorageSignaturePubKeyBytes = 15;
string p2pStorageSignaturePubKeyAsHex = 16;
string signature = 17;
string feeTxId = 18;
}
message TradeStatistics {
int64 TTL = 1;
string currency = 2;
Offer.Direction direction = 3;
int64 trade_price = 4;
int64 trade_amount = 5;
int64 trade_date = 6;
string payment_method = 7;
int64 offer_date = 8;
bool use_market_based_price = 9;
double 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;
}
message MailboxStoragePayload {
int64 TTL = 1;
PrefixedSealedAndSignedMessage prefixedSealedAndSignedMessage = 2;
bytes senderPubKeyForAddOperationBytes = 3;
bytes receiverPubKeyForRemoveOperationBytes = 4;
}
message Offer {
enum Direction {
BUY = 0;
SELL = 1;
}
enum State {
UNDEFINED = 0;
OFFER_FEE_PAID = 1;
AVAILABLE = 2;
NOT_AVAILABLE = 3;
REMOVED = 4;
OFFERER_OFFLINE = 5;
}
int64 TTL = 1;
Direction direction = 2;
string currencyCode = 3;
string paymentMethodName = 4;
string countryCode = 5;
repeated string acceptedCountryCodes = 6;
string bankId = 7;
repeated string acceptedBankIds = 8;
repeated NodeAddress arbitratorNodeAddresses = 9;
string id = 10;
int64 date = 11;
int64 protocolVersion = 12;
bool useMarketBasedPrice = 13;
int64 fiatPrice = 14;
double marketPriceMargin = 15;
int64 amount = 16;
int64 minAmount = 17;
NodeAddress offererNodeAddress = 18;
PubKeyRing pubKeyRing = 19;
string offererPaymentAccountId = 20;
string offerFeePaymentTxID = 21;
string versionNr = 22;
int64 blockHeightAtOfferCreation = 23;
int64 txFee = 24;
int64 createOfferFee = 25;
int64 securityDeposit = 26;
int64 maxTradeLimit = 27;
int64 maxTradePeriod = 28;
bool useAutoClose = 29;
bool useReOpenAfterAutoClose = 30;
int64 lowerClosePrice = 31;
int64 upperClosePrice = 32;
bool isPrivateOffer = 33;
string hashOfChallenge = 34;
map<string, string> extraDataMap = 35;
}
// stop storagepayloads
message PrefixedSealedAndSignedMessage {
int64 message_version = 1;
NodeAddress node_address = 2;
@ -123,80 +305,382 @@ message SealedAndSigned {
bytes sig_public_key_bytes = 4;
}
public final byte[] encryptedSecretKey;
public final byte[] encryptedPayloadWithHmac;
public final byte[] signature;
public transient PublicKey sigPublicKey;
private final byte[] sigPublicKeyBytes;
/*
public ProtectedStorageEntry(StoragePayload storagePayload, PublicKey ownerPubKey, int sequenceNumber, byte[] signature) {
this.storagePayload = storagePayload;
this.ownerPubKey = ownerPubKey;
this.sequenceNumber = sequenceNumber;
this.signature = signature;
this.creationTimeStamp = System.currentTimeMillis();
this.ownerPubKeyBytes = new X509EncodedKeySpec(this.ownerPubKey.getEncoded()).getEncoded();
message DepositTxPublishedMessage {
int32 message_version = 1;
string trade_id = 2;
bytes deposit_tx = 3;
NodeAddress sender_node_address = 4;
string uid = 5;
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
try {
in.defaultReadObject();
ownerPubKey = KeyFactory.getInstance(Sig.KEY_ALGO, "BC").generatePublic(new X509EncodedKeySpec(ownerPubKeyBytes));
checkCreationTimeStamp();
} catch (Throwable t) {
log.warn("Exception at readObject: " + t.getMessage());
}
// DisputeMessage
message DisputeCommunicationMessage {
int64 date = 1;
string trade_id = 2;
int32 trader_id = 3;
bool sender_is_trader = 4;
string message = 5;
repeated Attachment attachments = 6;
bool arrived = 7;
bool stored_in_mailbox = 8;
bool is_system_message = 9;
NodeAddress my_node_address = 10;
}
public StoragePayload getStoragePayload() {
return storagePayload;
message Attachment {
bytes bytes = 1;
string file_name = 2;
}
public void checkCreationTimeStamp() {
// We don't allow creation date in the future, but we cannot be too strict as clocks are not synced
// The 0 test is needed to be backward compatible as creationTimeStamp (timeStamp) was transient before 0.4.7
// TODO "|| creationTimeStamp == 0" can removed after we don't support 0.4.6 anymore
if (creationTimeStamp > System.currentTimeMillis() || creationTimeStamp == 0)
creationTimeStamp = System.currentTimeMillis();
message DisputeResultMessage {
DisputeResult dispute_result = 1;
NodeAddress my_node_address = 2;
}
public void refreshTTL() {
creationTimeStamp = System.currentTimeMillis();
// payload
message DisputeResult {
enum DisputeFeePolicy {
LOSER = 0;
SPLIT = 1;
WAIVE = 2;
}
enum Winner {
BUYER = 0;
SELLER = 1;
STALE_MATE = 2;
}
// only append new values as we use the ordinal value
enum Reason {
OTHER = 0;
BUG = 1;
USABILITY = 2;
SCAM = 3;
PROTOCOL_VIOLATION = 4;
NO_REPLY = 5;
}
string trade_id = 1;
int32 trader_id = 2;
DisputeFeePolicy dispute_fee_policy = 3;
Winner winner = 4;
int32 reason_ordinal = 5;
bool tamper_proof_evidence = 6;
bool id_verification = 7;
bool screen_cast = 8;
string summary_notes = 9;
DisputeCommunicationMessage dispute_communication_message = 10;
bytes arbitrator_signature = 11;
int64 buyer_payout_amount = 12;
int64 seller_payout_amount = 13;
int64 arbitrator_payout_amount = 14;
string arbitrator_address_asstring = 15;
bytes arbitrator_pub_key = 16;
int64 close_date = 17;
bool is_loser_publisher = 18;
}
message OpenNewDisputeMessage {
Dispute dispute = 1;
NodeAddress my_node_address = 2;
}
public void backDate() {
creationTimeStamp -= storagePayload.getTTL() / 2;
message Dispute {
string trade_id = 1;
string id = 2;
int32 trader_id = 3;
bool dispute_opener_is_buyer = 4;
bool dispute_opener_is_offerer = 5;
int64 opening_date = 6;
PubKeyRing trader_pub_key_ring = 7;
int64 trade_date = 8;
Contract contract = 9;
bytes contract_hash = 10;
bytes deposit_tx_serialized = 11;
bytes payout_tx_serialized = 12;
string deposit_tx_id = 13;
string payout_tx_id = 14;
string contract_as_json = 15;
string offerer_contract_signature = 16;
string taker_contract_signature = 17;
PubKeyRing arbitrator_pub_key_ring = 18;
bool is_support_ticket = 19;
repeated DisputeCommunicationMessage dispute_communication_messages = 20;
bool is_closed = 21;
DisputeResult dispute_result = 22;
string dispute_payout_tx_id = 23;
}
public void updateSequenceNumber(int sequenceNumber) {
this.sequenceNumber = sequenceNumber;
message PubKeyRing {
bytes signature_pub_key_bytes = 1;
bytes encryption_pub_key_bytes = 2;
}
public void updateSignature(byte[] signature) {
this.signature = signature;
message Contract {
Offer offer = 1;
int64 trade_amount = 2;
int64 trade_price = 3;
string take_offer_fee_tx_i_d = 4;
NodeAddress arbitrator_node_address = 5;
bool is_buyer_offerer_and_seller_taker = 6;
string offerer_account_id = 7;
string taker_account_id = 8;
PaymentAccountContractData offerer_payment_account_contract_data = 9;
PaymentAccountContractData taker_payment_account_contract_data = 10;
PubKeyRing offerer_pub_key_ring = 11;
PubKeyRing taker_pub_key_ring = 12;
NodeAddress buyer_node_address = 13;
NodeAddress seller_node_address = 14;
string offerer_payout_addressstring = 15;
string taker_payout_addressstring = 16;
bytes offerer_btc_pub_key = 17;
bytes taker_btc_pub_key = 18;
}
public boolean isExpired() {
return (System.currentTimeMillis() - creationTimeStamp) > storagePayload.getTTL();
message PeerOpenedDisputeMessage {
Dispute dispute = 1;
NodeAddress my_node_address = 2;
}
message PeerPublishedPayoutTxMessage {
bytes transaction = 1;
string trade_id = 2;
NodeAddress my_node_address = 3;
}
// DisputeMessage
message MockMailboxPayload {
int32 message_version = 1;
string msg = 2;
NodeAddress sender_node_address = 3;
int64 ttl = 4;
string uid = 5;
}
@Override
public String toString() {
return "ProtectedStorageEntry{" +
"expirablePayload=" + storagePayload +
", creationTimeStamp=" + creationTimeStamp +
", sequenceNumber=" + sequenceNumber +
", ownerPubKey.hashCode()=" + (ownerPubKey != null ? ownerPubKey.hashCode() : "null") +
", signature.hashCode()=" + (signature != null ? Arrays.toString(signature).hashCode() : "null") +
'}';
message PayDepositRequest {
string trade_id = 1;
int64 trade_amount = 2;
int64 trade_price = 3;
bytes taker_multi_sig_pub_key = 4;
Coin tx_fee = 5;
Coin take_offer_fee = 6;
repeated RawTransactionInput raw_transaction_inputs = 7;
int64 change_output_value = 8;
string change_output_address = 9;
string taker_payout_address_string = 10;
PubKeyRing taker_pub_key_ring = 11;
PaymentAccountContractData taker_payment_account_contract_data = 12;
string taker_account_id = 13;
string take_offer_fee_tx_id = 14;
repeated NodeAddress accepted_arbitrator_node_addresses = 15;
NodeAddress arbitrator_node_address = 16;
NodeAddress sender_node_address = 17;
string uid = 18;
}
message Coin {
int64 value = 1;
}
*/
message RawTransactionInput {
int64 index = 1;
bytes parent_transaction = 2;
int64 value = 3;
}
message PayoutTxFinalizedMessage {
string uid = 1;
int32 message_version = 2;
string trade_id = 3;
bytes payout_tx = 4;
NodeAddress sender_node_address = 5;
}
message PrivateNotificationMessage {
int32 message_version = 1;
string uid = 2;
NodeAddress my_node_address = 3;
PrivateNotification private_notification = 4;
}
message PrivateNotification {
string message = 1;
string signature_as_base64 = 2;
bytes public_key_bytes = 3;
}
message OfferAvailabilityRequest {
int32 message_version = 1;
string offer_id = 2;
PubKeyRing pub_key_ring = 3;
int64 takers_trade_price = 4;
repeated int32 supported_capabilities = 5;
}
message OfferAvailabilityResponse {
int32 message_version = 1;
string offer_id = 2;
AvailabilityResult availability_result = 3;
repeated int32 supported_capabilities = 4;
}
enum AvailabilityResult {
UNKNOWN_FAILURE = 0; // 0 is the default value when something goes wrong, map it to failure
AVAILABLE = 1;
OFFER_TAKEN = 2;
PRICE_OUT_OF_TOLERANCE = 3;
MARKET_PRICE_NOT_AVAILABLE = 4;
NO_ARBITRATORS = 5;
USER_IGNORED = 6;
}
message FiatTransferStartedMessage {
int32 message_version = 1;
string trade_id = 2;
string buyer_payout_address = 3;
NodeAddress sender_node_address = 4;
string uid = 5;
}
message FinalizePayoutTxRequest {
int32 message_version = 1;
string trade_id = 2;
bytes seller_signature = 3;
string seller_payout_address = 4;
int64 lock_time_as_block_height = 5;
NodeAddress sender_node_address = 6;
string uid = 7;
}
message PublishDepositTxRequest {
int32 message_version = 1;
string trade_id = 2;
PaymentAccountContractData offerer_payment_account_contract_data = 3;
string offerer_account_id = 4;
string offerer_contract_as_json = 5;
string offerer_contract_signature = 6;
string offerer_payout_addressstring = 7;
bytes prepared_deposit_tx = 8;
repeated RawTransactionInput offerer_inputs = 9;
bytes offerer_multi_sig_pub_key = 10;
}
message PaymentAccountContractData {
string id = 1;
string payment_method_name = 2;
int64 max_trade_period = 3;
}
message AliPayAccountContractData {
PaymentAccountContractData payment_account_contract_data = 1;
string account_nr = 2;
}
message ChaseQuickPayAccountContractData {
PaymentAccountContractData payment_account_contract_data = 1;
string email = 2;
string holder_name = 3;
}
message ClearXchangeAccountContractData {
PaymentAccountContractData payment_account_contract_data = 1;
string holder_name = 2;
string email_or_mobile_nr = 3;
}
message CountryBasedPaymentAccountContractData {
PaymentAccountContractData payment_account_contract_data = 1;
string countryCode = 2;
}
message BankAccountContractData {
CountryBasedPaymentAccountContractData country_based_payment_account_contract_data = 1;
string holder_name = 2;
string bank_name = 3;
string bank_id = 4;
string branch_id = 5;
string account_nr = 6;
string account_type = 7;
string holder_tax_id = 8;
}
message NationalBankAccountContractData {
BankAccountContractData bank_account_contract_data = 1;
}
message SameBankAccountContractData {
BankAccountContractData bank_account_contract_data = 1;
}
message SpecificBanksAccountContractData {
BankAccountContractData bank_account_contract_data = 1;
repeated string accepted_banks = 2;
}
message CashDepositAccountContractData {
CountryBasedPaymentAccountContractData country_based_payment_account_contract_data = 1;
string holder_name = 2;
string holder_email = 3;
string bank_name = 4;
string bank_id = 5;
string branch_id = 6;
string account_nr = 7;
string account_type = 8;
string requirements = 9;
string holder_tax_id = 10;
}
message SepaAccountContractData {
CountryBasedPaymentAccountContractData country_based_payment_account_contract_data = 1;
string holder_name = 2;
string iban = 3;
string bic = 4;
repeated string accepted_country_codes = 5;
}
message CryptoCurrencyAccountContractData {
PaymentAccountContractData payment_account_contract_data = 1;
string address = 2;
}
message FasterPaymentsAccountContractData {
PaymentAccountContractData payment_account_contract_data = 1;
string sort_code = 2;
string account_nr = 3;
}
message InteracETransferAccountContractData {
PaymentAccountContractData payment_account_contract_data = 1;
string email = 2;
string holder_name = 3;
string question = 4;
string answer = 5;
}
message OKPayAccountContractData {
PaymentAccountContractData payment_account_contract_data = 1;
string account_nr = 2;
}
message PerfectMoneyAccountContractData {
PaymentAccountContractData payment_account_contract_data = 1;
string account_nr = 2;
}
message SwishAccountContractData {
PaymentAccountContractData payment_account_contract_data = 1;
string mobile_nr = 2;
string holder_name = 3;
}
message USPostalMoneyOrderAccountContractData {
PaymentAccountContractData payment_account_contract_data = 1;
string postal_address = 2;
string holder_name = 3;
}
message ProtectedMailboxStorageEntry {
ProtectedStorageEntry entry = 1;
bytes receivers_pub_key_bytes = 2;
}

View file

@ -25,7 +25,10 @@ import org.slf4j.LoggerFactory;
import java.io.IOException;
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.Arrays;
import java.util.concurrent.TimeUnit;
@ -47,17 +50,26 @@ public final class Alert implements StoragePayload {
this.message = message;
this.isUpdateInfo = isUpdateInfo;
this.version = version;
init();
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
try {
in.defaultReadObject();
storagePublicKey = KeyFactory.getInstance(Sig.KEY_ALGO, "BC").generatePublic(new X509EncodedKeySpec(storagePublicKeyBytes));
init();
} catch (Throwable t) {
log.warn("Exception at readObject: " + t.getMessage());
}
}
private void init() {
try {
storagePublicKey = KeyFactory.getInstance(Sig.KEY_ALGO, "BC").generatePublic(new X509EncodedKeySpec(storagePublicKeyBytes));
} catch (InvalidKeySpecException | NoSuchAlgorithmException | NoSuchProviderException e) {
log.error("Couldn't create the storage public key", e);
}
}
public void setSigAndPubKey(String signatureAsBase64, PublicKey storagePublicKey) {
this.signatureAsBase64 = signatureAsBase64;
this.storagePublicKey = storagePublicKey;

View file

@ -25,7 +25,10 @@ import org.slf4j.LoggerFactory;
import java.io.IOException;
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.Arrays;
@ -43,15 +46,30 @@ public final class PrivateNotification implements Payload {
this.message = message;
}
public PrivateNotification(String message, String signatureAsBase64, byte[] publicKeyBytes) {
this(message);
this.signatureAsBase64 = signatureAsBase64;
this.publicKeyBytes = publicKeyBytes;
init();
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
try {
in.defaultReadObject();
publicKey = KeyFactory.getInstance(Sig.KEY_ALGO, "BC").generatePublic(new X509EncodedKeySpec(publicKeyBytes));
init();
} catch (Throwable t) {
log.warn("Exception at readObject: " + t.getMessage());
}
}
private void init() {
try {
publicKey = KeyFactory.getInstance(Sig.KEY_ALGO, "BC").generatePublic(new X509EncodedKeySpec(publicKeyBytes));
} catch (InvalidKeySpecException | NoSuchAlgorithmException | NoSuchProviderException e) {
log.error("Could not create public key from bytes", e);
}
}
public void setSigAndPubKey(String signatureAsBase64, PublicKey storagePublicKey) {
this.signatureAsBase64 = signatureAsBase64;
this.publicKey = storagePublicKey;

View file

@ -26,6 +26,8 @@ import io.bitsquare.trade.Contract;
import javafx.beans.property.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -36,10 +38,11 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
@Slf4j
@EqualsAndHashCode
public final class Dispute implements Payload {
// That object is sent over the wire, so we need to take care of version compatibility.
private static final long serialVersionUID = Version.P2P_NETWORK_VERSION;
private static final Logger log = LoggerFactory.getLogger(Dispute.class);
///////////////////////////////////////////////////////////////////////////////////////////
// Fields
@ -125,19 +128,24 @@ public final class Dispute implements Payload {
this.openingDate = new Date().getTime();
id = tradeId + "_" + traderId;
fillInTransients();
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
try {
in.defaultReadObject();
disputeCommunicationMessagesAsObservableList = FXCollections.observableArrayList(disputeCommunicationMessages);
disputeResultProperty = new SimpleObjectProperty<>(disputeResult);
isClosedProperty = new SimpleBooleanProperty(isClosed);
fillInTransients();
} catch (Throwable t) {
log.warn("Cannot be deserialized." + t.getMessage());
}
}
private void fillInTransients() {
disputeCommunicationMessagesAsObservableList = FXCollections.observableArrayList(disputeCommunicationMessages);
disputeResultProperty = new SimpleObjectProperty<>(disputeResult);
isClosedProperty = new SimpleBooleanProperty(isClosed);
}
public void addDisputeMessage(DisputeCommunicationMessage disputeCommunicationMessage) {
if (!disputeCommunicationMessages.contains(disputeCommunicationMessage)) {
disputeCommunicationMessages.add(disputeCommunicationMessage);
@ -291,77 +299,6 @@ public final class Dispute implements Payload {
return disputePayoutTxId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Dispute)) return false;
Dispute dispute = (Dispute) o;
if (traderId != dispute.traderId) return false;
if (disputeOpenerIsBuyer != dispute.disputeOpenerIsBuyer) return false;
if (disputeOpenerIsOfferer != dispute.disputeOpenerIsOfferer) return false;
if (openingDate != dispute.openingDate) return false;
if (tradeDate != dispute.tradeDate) return false;
if (isSupportTicket != dispute.isSupportTicket) return false;
if (isClosed != dispute.isClosed) return false;
if (tradeId != null ? !tradeId.equals(dispute.tradeId) : dispute.tradeId != null) return false;
if (id != null ? !id.equals(dispute.id) : dispute.id != null) return false;
if (traderPubKeyRing != null ? !traderPubKeyRing.equals(dispute.traderPubKeyRing) : dispute.traderPubKeyRing != null)
return false;
if (contract != null ? !contract.equals(dispute.contract) : dispute.contract != null) return false;
if (!Arrays.equals(contractHash, dispute.contractHash)) return false;
if (!Arrays.equals(depositTxSerialized, dispute.depositTxSerialized)) return false;
if (!Arrays.equals(payoutTxSerialized, dispute.payoutTxSerialized)) return false;
if (depositTxId != null ? !depositTxId.equals(dispute.depositTxId) : dispute.depositTxId != null) return false;
if (payoutTxId != null ? !payoutTxId.equals(dispute.payoutTxId) : dispute.payoutTxId != null) return false;
if (contractAsJson != null ? !contractAsJson.equals(dispute.contractAsJson) : dispute.contractAsJson != null)
return false;
if (offererContractSignature != null ? !offererContractSignature.equals(dispute.offererContractSignature) : dispute.offererContractSignature != null)
return false;
if (takerContractSignature != null ? !takerContractSignature.equals(dispute.takerContractSignature) : dispute.takerContractSignature != null)
return false;
if (arbitratorPubKeyRing != null ? !arbitratorPubKeyRing.equals(dispute.arbitratorPubKeyRing) : dispute.arbitratorPubKeyRing != null)
return false;
if (disputeCommunicationMessages != null ? !disputeCommunicationMessages.equals(dispute.disputeCommunicationMessages) : dispute.disputeCommunicationMessages != null)
return false;
if (disputeResult != null ? !disputeResult.equals(dispute.disputeResult) : dispute.disputeResult != null)
return false;
if (disputePayoutTxId != null ? !disputePayoutTxId.equals(dispute.disputePayoutTxId) : dispute.disputePayoutTxId != null)
return false;
return !(storage != null ? !storage.equals(dispute.storage) : dispute.storage != null);
}
@Override
public int hashCode() {
int result = tradeId != null ? tradeId.hashCode() : 0;
result = 31 * result + (id != null ? id.hashCode() : 0);
result = 31 * result + traderId;
result = 31 * result + (disputeOpenerIsBuyer ? 1 : 0);
result = 31 * result + (disputeOpenerIsOfferer ? 1 : 0);
result = 31 * result + (int) (openingDate ^ (openingDate >>> 32));
result = 31 * result + (traderPubKeyRing != null ? traderPubKeyRing.hashCode() : 0);
result = 31 * result + (int) (tradeDate ^ (tradeDate >>> 32));
result = 31 * result + (contract != null ? contract.hashCode() : 0);
result = 31 * result + (contractHash != null ? Arrays.hashCode(contractHash) : 0);
result = 31 * result + (depositTxSerialized != null ? Arrays.hashCode(depositTxSerialized) : 0);
result = 31 * result + (payoutTxSerialized != null ? Arrays.hashCode(payoutTxSerialized) : 0);
result = 31 * result + (depositTxId != null ? depositTxId.hashCode() : 0);
result = 31 * result + (payoutTxId != null ? payoutTxId.hashCode() : 0);
result = 31 * result + (contractAsJson != null ? contractAsJson.hashCode() : 0);
result = 31 * result + (offererContractSignature != null ? offererContractSignature.hashCode() : 0);
result = 31 * result + (takerContractSignature != null ? takerContractSignature.hashCode() : 0);
result = 31 * result + (arbitratorPubKeyRing != null ? arbitratorPubKeyRing.hashCode() : 0);
result = 31 * result + (isSupportTicket ? 1 : 0);
result = 31 * result + (disputeCommunicationMessages != null ? disputeCommunicationMessages.hashCode() : 0);
result = 31 * result + (isClosed ? 1 : 0);
result = 31 * result + (disputeResult != null ? disputeResult.hashCode() : 0);
result = 31 * result + (disputePayoutTxId != null ? disputePayoutTxId.hashCode() : 0);
result = 31 * result + (storage != null ? storage.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Dispute{" +

View file

@ -51,25 +51,39 @@ public final class DisputeCommunicationMessage extends DisputeMessage {
transient private BooleanProperty arrivedProperty = new SimpleBooleanProperty();
transient private BooleanProperty storedInMailboxProperty = new SimpleBooleanProperty();
public DisputeCommunicationMessage(String tradeId, int traderId, boolean senderIsTrader, String message, NodeAddress myNodeAddress) {
public DisputeCommunicationMessage(String tradeId, int traderId, boolean senderIsTrader, String message,
NodeAddress myNodeAddress, long date, boolean arrived, boolean storedInMailbox) {
this.tradeId = tradeId;
this.traderId = traderId;
this.senderIsTrader = senderIsTrader;
this.message = message;
this.myNodeAddress = myNodeAddress;
date = new Date().getTime();
this.date = date;
this.arrived = arrived;
this.storedInMailbox = storedInMailbox;
updateBooleanProperties();
}
public DisputeCommunicationMessage(String tradeId, int traderId, boolean senderIsTrader, String message,
NodeAddress myNodeAddress) {
this(tradeId, traderId, senderIsTrader, message, myNodeAddress, new Date().getTime(), false, false);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
try {
in.defaultReadObject();
arrivedProperty = new SimpleBooleanProperty(arrived);
storedInMailboxProperty = new SimpleBooleanProperty(storedInMailbox);
updateBooleanProperties();
} catch (Throwable t) {
log.warn("Cannot be deserialized." + t.getMessage());
}
}
private void updateBooleanProperties() {
arrivedProperty = new SimpleBooleanProperty(arrived);
storedInMailboxProperty = new SimpleBooleanProperty(storedInMailbox);
}
@Override
public NodeAddress getSenderNodeAddress() {
return myNodeAddress;

View file

@ -25,7 +25,15 @@ import java.util.UUID;
public abstract class DisputeMessage implements MailboxMessage {
//TODO add serialVersionUID also in superclasses as changes would break compatibility
private final int messageVersion = Version.getP2PMessageVersion();
private final String uid = UUID.randomUUID().toString();
private final String uid;
public DisputeMessage(String uid) {
this.uid = uid;
}
public DisputeMessage() {
uid = UUID.randomUUID().toString();
}
@Override
public int getMessageVersion() {

View file

@ -29,6 +29,13 @@ public final class OpenNewDisputeMessage extends DisputeMessage {
private final NodeAddress myNodeAddress;
public OpenNewDisputeMessage(Dispute dispute, NodeAddress myNodeAddress) {
super();
this.dispute = dispute;
this.myNodeAddress = myNodeAddress;
}
public OpenNewDisputeMessage(Dispute dispute, NodeAddress myNodeAddress, String uid) {
super(uid);
this.dispute = dispute;
this.myNodeAddress = myNodeAddress;
}

View file

@ -33,6 +33,12 @@ public final class PeerOpenedDisputeMessage extends DisputeMessage {
this.myNodeAddress = myNodeAddress;
}
public PeerOpenedDisputeMessage(Dispute dispute, NodeAddress myNodeAddress, String uid) {
super(uid);
this.dispute = dispute;
this.myNodeAddress = myNodeAddress;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;

View file

@ -31,6 +31,14 @@ public final class PeerPublishedPayoutTxMessage extends DisputeMessage {
private final NodeAddress myNodeAddress;
public PeerPublishedPayoutTxMessage(byte[] transaction, String tradeId, NodeAddress myNodeAddress) {
super();
this.transaction = transaction;
this.tradeId = tradeId;
this.myNodeAddress = myNodeAddress;
}
public PeerPublishedPayoutTxMessage(byte[] transaction, String tradeId, NodeAddress myNodeAddress, String uid) {
super(uid);
this.transaction = transaction;
this.tradeId = tradeId;
this.myNodeAddress = myNodeAddress;

View file

@ -110,20 +110,26 @@ public final class CompensationRequestPayload implements LazyProcessedStoragePay
this.p2pStorageSignaturePubKey = p2pStorageSignaturePubKey;
this.p2pStorageSignaturePubKeyBytes = new X509EncodedKeySpec(p2pStorageSignaturePubKey.getEncoded()).getEncoded();
p2pStorageSignaturePubKeyAsHex = Utils.HEX.encode(p2pStorageSignaturePubKey.getEncoded());
init();
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
try {
in.defaultReadObject();
p2pStorageSignaturePubKey = KeyFactory.getInstance(Sig.KEY_ALGO, "BC").generatePublic(new X509EncodedKeySpec(p2pStorageSignaturePubKeyBytes));
} catch (InvalidKeySpecException | NoSuchAlgorithmException | NoSuchProviderException e) {
e.printStackTrace();
log.error(e.getMessage());
init();
} catch (Throwable t) {
log.warn("Cannot be deserialized." + t.getMessage());
}
}
private void init() {
try {
p2pStorageSignaturePubKey = KeyFactory.getInstance(Sig.KEY_ALGO, "BC").generatePublic(new X509EncodedKeySpec(p2pStorageSignaturePubKeyBytes));
} catch (InvalidKeySpecException | NoSuchAlgorithmException | NoSuchProviderException e) {
log.error("Couldn't create the p2p storage public key", e);
}
}
public void setSignature(String signature) {
this.signature = signature;
}

View file

@ -25,7 +25,10 @@ import org.slf4j.LoggerFactory;
import java.io.IOException;
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.ArrayList;
import java.util.Arrays;
@ -49,17 +52,26 @@ public final class Filter implements StoragePayload {
this.bannedOfferIds = bannedOfferIds;
this.bannedNodeAddress = bannedNodeAddress;
this.bannedPaymentAccounts = bannedPaymentAccounts;
init();
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
try {
in.defaultReadObject();
publicKey = KeyFactory.getInstance(Sig.KEY_ALGO, "BC").generatePublic(new X509EncodedKeySpec(publicKeyBytes));
init();
} catch (Throwable t) {
log.warn("Exception at readObject: " + t.getMessage());
}
}
private void init() {
try {
publicKey = KeyFactory.getInstance(Sig.KEY_ALGO, "BC").generatePublic(new X509EncodedKeySpec(publicKeyBytes));
} catch (InvalidKeySpecException | NoSuchAlgorithmException | NoSuchProviderException e) {
log.error("Couldn't create the storage public key", e);
}
}
public void setSigAndPubKey(String signatureAsBase64, PublicKey storagePublicKey) {
this.signatureAsBase64 = signatureAsBase64;
this.publicKey = storagePublicKey;

View file

@ -25,13 +25,15 @@ public final class CryptoCurrencyAccountContractData extends PaymentAccountContr
private String address;
// TODO Not needed. Remove when we have an update which breaks backward compatibility
private String paymentId;
public CryptoCurrencyAccountContractData(String paymentMethod, String id, long maxTradePeriod) {
super(paymentMethod, id, maxTradePeriod);
}
public CryptoCurrencyAccountContractData(String paymentMethod, String id, long maxTradePeriod, String address) {
super(paymentMethod, id, maxTradePeriod);
this.address = address;
}
public void setAddress(String address) {
this.address = address;
}

View file

@ -30,6 +30,13 @@ public final class FasterPaymentsAccountContractData extends PaymentAccountContr
super(paymentMethod, id, maxTradePeriod);
}
public FasterPaymentsAccountContractData(String paymentMethod, String id, long maxTradePeriod,
String sortCode, String accountNr) {
super(paymentMethod, id, maxTradePeriod);
this.sortCode = sortCode;
this.accountNr = accountNr;
}
public void setAccountNr(String accountNr) {
this.accountNr = accountNr;
}

View file

@ -32,6 +32,15 @@ public final class InteracETransferAccountContractData extends PaymentAccountCon
super(paymentMethod, id, maxTradePeriod);
}
public InteracETransferAccountContractData(String paymentMethodName, String id, long maxTradePeriod,
String email, String holderName, String question, String answer) {
super(paymentMethodName, id, maxTradePeriod);
this.email = email;
this.holderName = holderName;
this.question = question;
this.answer = answer;
}
public void setEmail(String email) {
this.email = email;
}

View file

@ -29,6 +29,11 @@ public final class OKPayAccountContractData extends PaymentAccountContractData {
super(paymentMethod, id, maxTradePeriod);
}
public OKPayAccountContractData(String paymentMethodName, String id, long maxTradePeriod, String accountNr) {
super(paymentMethodName, id, maxTradePeriod);
this.accountNr = accountNr;
}
public void setAccountNr(String accountNr) {
this.accountNr = accountNr;
}

View file

@ -29,6 +29,11 @@ public final class PerfectMoneyAccountContractData extends PaymentAccountContrac
super(paymentMethod, id, maxTradePeriod);
}
public PerfectMoneyAccountContractData(String paymentMethodName, String id, long maxTradePeriod, String accountNr) {
super(paymentMethodName, id, maxTradePeriod);
this.accountNr = accountNr;
}
public void setAccountNr(String accountNr) {
this.accountNr = accountNr;
}

View file

@ -30,6 +30,13 @@ public final class SwishAccountContractData extends PaymentAccountContractData {
super(paymentMethod, id, maxTradePeriod);
}
public SwishAccountContractData(String paymentMethodName, String id, long maxTradePeriod,
String mobileNr, String holderName) {
super(paymentMethodName, id, maxTradePeriod);
this.mobileNr = mobileNr;
this.holderName = holderName;
}
public void setMobileNr(String mobileNr) {
this.mobileNr = mobileNr;
}

View file

@ -31,6 +31,13 @@ public final class USPostalMoneyOrderAccountContractData extends PaymentAccountC
super(paymentMethod, id, maxTradePeriod);
}
public USPostalMoneyOrderAccountContractData(String paymentMethodName, String id, long maxTradePeriod,
String postalAddress, String holderName) {
super(paymentMethodName, id, maxTradePeriod);
this.postalAddress = postalAddress;
this.holderName = holderName;
}
public void setPostalAddress(String postalAddress) {
this.postalAddress = postalAddress;
}

View file

@ -254,24 +254,27 @@ public final class Offer implements StoragePayload, RequiresOwnerIsOnlinePayload
date = new Date().getTime();
setState(State.UNDEFINED);
decimalFormat = new DecimalFormat("#.#");
decimalFormat.setMaximumFractionDigits(Fiat.SMALLEST_UNIT_EXPONENT);
init();
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
try {
in.defaultReadObject();
stateProperty = new SimpleObjectProperty<>(State.UNDEFINED);
// we don't need to fill it as the error message is only relevant locally, so we don't store it in the transmitted object
errorMessageProperty = new SimpleStringProperty();
decimalFormat = new DecimalFormat("#.#");
decimalFormat.setMaximumFractionDigits(Fiat.SMALLEST_UNIT_EXPONENT);
init();
} catch (Throwable t) {
log.warn("Cannot be deserialized." + t.getMessage());
}
}
private void init() {
stateProperty = new SimpleObjectProperty<>(State.UNDEFINED);
// we don't need to fill it as the error message is only relevant locally, so we don't store it in the transmitted object
errorMessageProperty = new SimpleStringProperty();
decimalFormat = new DecimalFormat("#.#");
decimalFormat.setMaximumFractionDigits(Fiat.SMALLEST_UNIT_EXPONENT);
}
@Override
public NodeAddress getOwnerNodeAddress() {
return offererNodeAddress;

View file

@ -20,13 +20,15 @@ package io.bitsquare.trade.protocol.availability.messages;
import io.bitsquare.app.Capabilities;
import io.bitsquare.app.Version;
import io.bitsquare.common.wire.proto.Messages;
import io.bitsquare.p2p.ProtoBufferMessage;
import io.bitsquare.p2p.messaging.SupportedCapabilitiesMessage;
import io.bitsquare.trade.protocol.availability.AvailabilityResult;
import javax.annotation.Nullable;
import java.util.ArrayList;
// We add here the SupportedCapabilitiesMessage interface as that message always predates a direct connection
// We add here the SupportedCapabilitiesMessage interface as that message always predates a direct connection
// to the trading peer
public final class OfferAvailabilityResponse extends OfferMessage implements SupportedCapabilitiesMessage {
// That object is sent over the wire, so we need to take care of version compatibility.
@ -57,4 +59,4 @@ public final class OfferAvailabilityResponse extends OfferMessage implements Sup
"availabilityResult=" + availabilityResult +
"} " + super.toString();
}
}
}

View file

@ -34,11 +34,15 @@ public final class DepositTxPublishedMessage extends TradeMessage implements Mai
private final NodeAddress senderNodeAddress;
private final String uid;
public DepositTxPublishedMessage(String tradeId, byte[] depositTx, NodeAddress senderNodeAddress) {
public DepositTxPublishedMessage(String tradeId, byte[] depositTx, NodeAddress senderNodeAddress, String uid) {
super(tradeId);
this.depositTx = depositTx;
this.senderNodeAddress = senderNodeAddress;
uid = UUID.randomUUID().toString();
this.uid = uid;
}
public DepositTxPublishedMessage(String tradeId, byte[] depositTx, NodeAddress senderNodeAddress) {
this(tradeId, depositTx, senderNodeAddress, UUID.randomUUID().toString());
}
@Override

View file

@ -25,7 +25,7 @@ import javax.annotation.concurrent.Immutable;
import java.util.UUID;
@Immutable
public final class FiatTransferStartedMessage extends TradeMessage implements MailboxMessage {
public final class FiatTransferStartedMessage extends TradeMessage implements MailboxMessage {
// That object is sent over the wire, so we need to take care of version compatibility.
private static final long serialVersionUID = Version.P2P_NETWORK_VERSION;
@ -33,11 +33,16 @@ public final class FiatTransferStartedMessage extends TradeMessage implements Ma
private final NodeAddress senderNodeAddress;
private final String uid;
public FiatTransferStartedMessage(String tradeId, String buyerPayoutAddress, NodeAddress senderNodeAddress) {
public FiatTransferStartedMessage(String tradeId, String buyerPayoutAddress,
NodeAddress senderNodeAddress, String uid) {
super(tradeId);
this.buyerPayoutAddress = buyerPayoutAddress;
this.senderNodeAddress = senderNodeAddress;
uid = UUID.randomUUID().toString();
this.uid = uid;
}
public FiatTransferStartedMessage(String tradeId, String buyerPayoutAddress, NodeAddress senderNodeAddress) {
this(tradeId, buyerPayoutAddress, senderNodeAddress, UUID.randomUUID().toString());
}
@Override

View file

@ -41,12 +41,22 @@ public final class FinalizePayoutTxRequest extends TradeMessage implements Mailb
String sellerPayoutAddress,
long lockTimeAsBlockHeight,
NodeAddress senderNodeAddress) {
this(tradeId, sellerSignature, sellerPayoutAddress, lockTimeAsBlockHeight, senderNodeAddress,
UUID.randomUUID().toString());
}
public FinalizePayoutTxRequest(String tradeId,
byte[] sellerSignature,
String sellerPayoutAddress,
long lockTimeAsBlockHeight,
NodeAddress senderNodeAddress,
String uid) {
super(tradeId);
this.sellerSignature = sellerSignature;
this.sellerPayoutAddress = sellerPayoutAddress;
this.lockTimeAsBlockHeight = lockTimeAsBlockHeight;
this.senderNodeAddress = senderNodeAddress;
uid = UUID.randomUUID().toString();
this.uid = uid;
}
@Override

View file

@ -35,10 +35,14 @@ public final class PayoutTxFinalizedMessage extends TradeMessage implements Mail
private final String uid;
public PayoutTxFinalizedMessage(String tradeId, byte[] payoutTx, NodeAddress senderNodeAddress) {
this(tradeId, payoutTx, senderNodeAddress, UUID.randomUUID().toString());
}
public PayoutTxFinalizedMessage(String tradeId, byte[] payoutTx, NodeAddress senderNodeAddress, String uid) {
super(tradeId);
this.payoutTx = payoutTx;
this.senderNodeAddress = senderNodeAddress;
uid = UUID.randomUUID().toString();
this.uid = uid;
}
@Override

View file

@ -1,7 +1,11 @@
package io.bitsquare.p2p;
import io.bitsquare.common.wire.proto.Messages;
import java.io.Serializable;
public interface Message extends Serializable {
int getMessageVersion();
//Messages.Envelope toProtoBuf();
}

View file

@ -1,16 +1,27 @@
package io.bitsquare.p2p;
import io.bitsquare.common.wire.proto.Messages;
import com.google.protobuf.ByteString;
import io.bitsquare.common.crypto.SealedAndSigned;
import io.bitsquare.p2p.messaging.PrefixedSealedAndSignedMessage;
import io.bitsquare.p2p.network.messages.CloseConnectionMessage;
import io.bitsquare.common.wire.proto.Messages;
import io.bitsquare.p2p.peers.getdata.messages.GetDataRequest;
import io.bitsquare.p2p.peers.getdata.messages.GetDataResponse;
import io.bitsquare.p2p.peers.getdata.messages.GetUpdatedDataRequest;
import io.bitsquare.p2p.peers.getdata.messages.PreliminaryGetDataRequest;
import io.bitsquare.p2p.peers.keepalive.messages.Ping;
import io.bitsquare.p2p.peers.keepalive.messages.Pong;
import io.bitsquare.p2p.peers.peerexchange.Peer;
import io.bitsquare.p2p.peers.peerexchange.messages.GetPeersRequest;
import io.bitsquare.p2p.peers.peerexchange.messages.GetPeersResponse;
import io.bitsquare.p2p.storage.P2PDataStorage;
import io.bitsquare.p2p.storage.messages.RefreshTTLMessage;
import io.bitsquare.p2p.storage.storageentry.ProtectedStorageEntry;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
/**
@ -19,9 +30,20 @@ import java.util.stream.Collectors;
public class ProtoBufferUtilities {
public static boolean isPrefixedSealedAndSignedMessage(Messages.Envelope envelope) {
return false;
return !Messages.PrefixedSealedAndSignedMessage.getDefaultInstance()
.equals(envelope.getPrefixedSealedAndSignedMessage());
}
public static PrefixedSealedAndSignedMessage createPrefixedSealedAndSignedMessage(Messages.Envelope envelope) {
Messages.PrefixedSealedAndSignedMessage msg = envelope.getPrefixedSealedAndSignedMessage();
NodeAddress nodeAddress = new NodeAddress(msg.getNodeAddress().getHostName(), msg.getNodeAddress().getPort());
SealedAndSigned sealedAndSigned = new SealedAndSigned(msg.getSealedAndSigned().getEncryptedSecretKey().toByteArray(),
msg.getSealedAndSigned().getEncryptedPayloadWithHmac().toByteArray(),
msg.getSealedAndSigned().getSignature().toByteArray(), msg.getSealedAndSigned().getSigPublicKeyBytes().toByteArray());
return new PrefixedSealedAndSignedMessage(nodeAddress, sealedAndSigned, msg.getAddressPrefixHash().toByteArray());
}
public static boolean isSendersNodeAddressMessage(Messages.Envelope envelope) {
return false;
}
@ -36,15 +58,67 @@ public class ProtoBufferUtilities {
envelope.getGetDataResponse().getDataSetList()
.stream()
.map(protectedStorageEntry ->
new ProtectedStorageEntry(null, null, 0, null)).collect(Collectors.toList()));
new ProtectedStorageEntry(null, new byte[]{}, 0, null)).collect(Collectors.toList()));
return new GetDataResponse(set, envelope.getGetDataResponse().getRequestNonce(), envelope.getGetDataResponse().getIsGetUpdatedDataResponse());
}
// This is an interface, maybe not needed
public static boolean isGetDataRequest(Messages.Envelope envelope) {
return false;
return isGetUpdatedDataRequest(envelope) || isPreliminaryGetDataRequest(envelope);
}
public static boolean isPreliminaryGetDataRequest(Messages.Envelope envelope) {
return !Messages.PreliminaryGetDataRequest.getDefaultInstance().equals(envelope.getPreliminaryGetDataRequest());
}
private static PreliminaryGetDataRequest createPreliminaryGetDataRequest(Messages.Envelope envelope) {
return new PreliminaryGetDataRequest(envelope.getPreliminaryGetDataRequest().getNonce(),
getByteSet(envelope.getPreliminaryGetDataRequest().getExcludedKeysList()));
}
public static boolean isGetUpdatedDataRequest(Messages.Envelope envelope) {
return !Messages.GetUpdatedDataRequest.getDefaultInstance().equals(envelope.getGetUpdatedDataRequest());
}
private static GetUpdatedDataRequest createGetUpdatedDataRequest(Messages.Envelope envelope) {
Messages.GetUpdatedDataRequest msg = envelope.getGetUpdatedDataRequest();
NodeAddress nodeAddress = new NodeAddress(msg.getSenderNodeAddress().getHostName(), msg.getSenderNodeAddress().getPort());
Set<byte[]> set = getByteSet(msg.getExcludedKeysList());
return new GetUpdatedDataRequest(nodeAddress, msg.getNonce(), set);
}
public static boolean isGetPeersRequest(Messages.Envelope envelope) {
return !Messages.GetPeersRequest.getDefaultInstance().equals(envelope.getGetPeersRequest());
}
private static GetPeersRequest createGetPeersRequest(Messages.Envelope envelope) {
Messages.GetPeersRequest msg = envelope.getGetPeersRequest();
NodeAddress nodeAddress = new NodeAddress(msg.getSenderNodeAddress().getHostName(), msg.getSenderNodeAddress().getPort());
HashSet<Peer> set =new HashSet<>(
msg.getReportedPeersList()
.stream()
.map(peer ->
new Peer(new NodeAddress(peer.getNodeAddress().getHostName(),
peer.getNodeAddress().getPort()))).collect(Collectors.toList()));
return new GetPeersRequest(nodeAddress, msg.getNonce(), set);
}
public static boolean isGetPeersResponse(Messages.Envelope envelope) {
return !Messages.GetPeersResponse.getDefaultInstance().equals(envelope.getGetPeersResponse());
}
private static GetPeersResponse createGetPeersResponse(Messages.Envelope envelope) {
Messages.GetPeersResponse msg = envelope.getGetPeersResponse();
HashSet<Peer> set =new HashSet<>(
msg.getReportedPeersList()
.stream()
.map(peer ->
new Peer(new NodeAddress(peer.getNodeAddress().getHostName(),
peer.getNodeAddress().getPort()))).collect(Collectors.toList()));
return new GetPeersResponse(msg.getRequestNonce(), set);
}
public static boolean isPing(Messages.Envelope envelope) {
return !Messages.Ping.getDefaultInstance().equals(envelope.getPing());
@ -81,6 +155,12 @@ public class ProtoBufferUtilities {
return new CloseConnectionMessage(envelope.getCloseConnectionMessage().getReason());
}
private static Set<byte[]> getByteSet(List<ByteString> byteStringList) {
return new HashSet<>(
byteStringList
.stream()
.map(ByteString::toByteArray).collect(Collectors.toList()));
}
public static Optional<Message> fromProtoBuf(Messages.Envelope envelope) {
if (isPing(envelope)) {
@ -93,7 +173,18 @@ public class ProtoBufferUtilities {
return Optional.of(createRefreshTTLMessage(envelope));
} else if (isCloseConnectionMessage(envelope)) {
return Optional.of(createCloseConnectionMessage(envelope));
} else if (isPrefixedSealedAndSignedMessage(envelope)) {
return Optional.of(createPrefixedSealedAndSignedMessage(envelope));
} else if (isGetUpdatedDataRequest(envelope)) {
return Optional.of(createGetUpdatedDataRequest(envelope));
} else if (isPreliminaryGetDataRequest(envelope)) {
return Optional.of(createPreliminaryGetDataRequest(envelope));
} else if (isGetPeersRequest(envelope)) {
return Optional.of(createGetPeersRequest(envelope));
} else if (isGetPeersResponse(envelope)) {
return Optional.of(createGetPeersResponse(envelope));
}
//envelope.
/*
else if (isPong(envelope)) {
return Optional.of(createPong(envelope));
@ -107,4 +198,5 @@ public class ProtoBufferUtilities {
}
}

View file

@ -18,13 +18,19 @@ public final class PrefixedSealedAndSignedMessage implements MailboxMessage, Sen
private final NodeAddress senderNodeAddress;
public final SealedAndSigned sealedAndSigned;
public final byte[] addressPrefixHash;
private final String uid = UUID.randomUUID().toString();
private final String uid;
public PrefixedSealedAndSignedMessage(NodeAddress senderNodeAddress, SealedAndSigned sealedAndSigned, byte[] addressPrefixHash) {
public PrefixedSealedAndSignedMessage(NodeAddress senderNodeAddress, SealedAndSigned sealedAndSigned,
byte[] addressPrefixHash, String uid) {
checkNotNull(senderNodeAddress, "senderNodeAddress must not be null at PrefixedSealedAndSignedMessage");
this.senderNodeAddress = senderNodeAddress;
this.sealedAndSigned = sealedAndSigned;
this.addressPrefixHash = addressPrefixHash;
this.uid = uid;
}
public PrefixedSealedAndSignedMessage(NodeAddress senderNodeAddress, SealedAndSigned sealedAndSigned, byte[] addressPrefixHash) {
this(senderNodeAddress, sealedAndSigned, addressPrefixHash, UUID.randomUUID().toString());
}
@Override

View file

@ -5,7 +5,7 @@ import io.bitsquare.common.wire.proto.Messages;
import io.bitsquare.p2p.Message;
import io.bitsquare.p2p.ProtoBufferMessage;
public final class CloseConnectionMessage implements Message, ProtoBufferMessage {
public final class CloseConnectionMessage implements Message {
// That object is sent over the wire, so we need to take care of version compatibility.
// We dont use the Version.NETWORK_PROTOCOL_VERSION here as we report also compatibility issues and
// a changed version would render that message invalid as well, so the peer cannot get notified about the problem.
@ -31,7 +31,7 @@ public final class CloseConnectionMessage implements Message, ProtoBufferMessage
'}';
}
@Override
//@Override
public Messages.Envelope toProtoBuf() {
Messages.Envelope.Builder envelopeBuilder = Messages.Envelope.newBuilder()
.setP2PNetworkVersion(Version.P2P_NETWORK_VERSION);

View file

@ -59,7 +59,7 @@ public final class PreliminaryGetDataRequest implements AnonymousMessage, GetDat
'}';
}
@Override
//@Override
public Messages.Envelope toProtoBuf() {
Messages.Envelope.Builder envelopeBuilder = Messages.Envelope.newBuilder().setP2PNetworkVersion(Version.P2P_NETWORK_VERSION);
Messages.PreliminaryGetDataRequest.Builder msgBuilder = envelopeBuilder.getPreliminaryGetDataRequestBuilder()

View file

@ -9,7 +9,7 @@ import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.HashSet;
public final class GetPeersResponse extends PeerExchangeMessage implements SupportedCapabilitiesMessage {
public final class GetPeersResponse extends PeerExchangeMessage implements SupportedCapabilitiesMessage {
// That object is sent over the wire, so we need to take care of version compatibility.
private static final long serialVersionUID = Version.P2P_NETWORK_VERSION;

View file

@ -11,7 +11,10 @@ import org.slf4j.LoggerFactory;
import java.io.IOException;
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.concurrent.TimeUnit;
@ -62,18 +65,27 @@ public final class MailboxStoragePayload implements StoragePayload {
this.receiverPubKeyForRemoveOperation = receiverPubKeyForRemoveOperation;
this.receiverPubKeyForRemoveOperationBytes = new X509EncodedKeySpec(this.receiverPubKeyForRemoveOperation.getEncoded()).getEncoded();
init();
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
try {
in.defaultReadObject();
senderPubKeyForAddOperation = KeyFactory.getInstance(Sig.KEY_ALGO, "BC").generatePublic(new X509EncodedKeySpec(senderPubKeyForAddOperationBytes));
receiverPubKeyForRemoveOperation = KeyFactory.getInstance(Sig.KEY_ALGO, "BC").generatePublic(new X509EncodedKeySpec(receiverPubKeyForRemoveOperationBytes));
init();
} catch (Throwable t) {
log.warn("Exception at readObject: " + t.getMessage() + "\nThis= " + this.toString());
}
}
private void init() {
try {
senderPubKeyForAddOperation = KeyFactory.getInstance(Sig.KEY_ALGO, "BC").generatePublic(new X509EncodedKeySpec(senderPubKeyForAddOperationBytes));
receiverPubKeyForRemoveOperation = KeyFactory.getInstance(Sig.KEY_ALGO, "BC").generatePublic(new X509EncodedKeySpec(receiverPubKeyForRemoveOperationBytes));
} catch (InvalidKeySpecException | NoSuchAlgorithmException | NoSuchProviderException e) {
log.error("Couldn't create the public keys", e);
}
}
@Override
public long getTTL() {
return TTL;

View file

@ -9,7 +9,10 @@ import org.slf4j.LoggerFactory;
import java.io.IOException;
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;
public class ProtectedMailboxStorageEntry extends ProtectedStorageEntry {
@ -25,23 +28,39 @@ public class ProtectedMailboxStorageEntry extends ProtectedStorageEntry {
return (MailboxStoragePayload) storagePayload;
}
public ProtectedMailboxStorageEntry(MailboxStoragePayload mailboxStoragePayload, PublicKey ownerStoragePubKey, int sequenceNumber, byte[] signature, PublicKey receiversPubKey) {
public ProtectedMailboxStorageEntry(MailboxStoragePayload mailboxStoragePayload, PublicKey ownerStoragePubKey,
int sequenceNumber, byte[] signature, PublicKey receiversPubKey) {
super(mailboxStoragePayload, ownerStoragePubKey, sequenceNumber, signature);
this.receiversPubKey = receiversPubKey;
this.receiversPubKeyBytes = new X509EncodedKeySpec(this.receiversPubKey.getEncoded()).getEncoded();
}
public ProtectedMailboxStorageEntry(MailboxStoragePayload mailboxStoragePayload, PublicKey ownerStoragePubKey,
int sequenceNumber, byte[] signature, byte[] receiversPubKeyBytes) {
super(mailboxStoragePayload, ownerStoragePubKey, sequenceNumber, signature);
this.receiversPubKeyBytes = receiversPubKeyBytes;
init();
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
try {
in.defaultReadObject();
receiversPubKey = KeyFactory.getInstance(Sig.KEY_ALGO, "BC").generatePublic(new X509EncodedKeySpec(receiversPubKeyBytes));
checkCreationTimeStamp();
init();
} catch (Throwable t) {
log.warn("Exception at readObject: " + t.getMessage());
}
}
private void init() {
try {
receiversPubKey = KeyFactory.getInstance(Sig.KEY_ALGO, "BC").generatePublic(new X509EncodedKeySpec(receiversPubKeyBytes));
checkCreationTimeStamp();
} catch (InvalidKeySpecException | NoSuchAlgorithmException | NoSuchProviderException e) {
log.error("Couldn't create the pubkey", e);
}
}
@Override
public String toString() {
return "ProtectedMailboxData{" +

View file

@ -10,7 +10,10 @@ import org.slf4j.LoggerFactory;
import java.io.IOException;
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.Arrays;
@ -37,16 +40,34 @@ public class ProtectedStorageEntry implements Payload {
this.ownerPubKeyBytes = new X509EncodedKeySpec(this.ownerPubKey.getEncoded()).getEncoded();
}
public ProtectedStorageEntry(StoragePayload storagePayload, byte[] ownerPubKeyBytes,
int sequenceNumber, byte[] signature) {
this.storagePayload = storagePayload;
this.sequenceNumber = sequenceNumber;
this.signature = signature;
this.creationTimeStamp = System.currentTimeMillis();
this.ownerPubKeyBytes = ownerPubKeyBytes;
init();
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
try {
in.defaultReadObject();
ownerPubKey = KeyFactory.getInstance(Sig.KEY_ALGO, "BC").generatePublic(new X509EncodedKeySpec(ownerPubKeyBytes));
checkCreationTimeStamp();
init();
} catch (Throwable t) {
log.warn("Exception at readObject: " + t.getMessage());
}
}
private void init() {
try {
ownerPubKey = KeyFactory.getInstance(Sig.KEY_ALGO, "BC").generatePublic(new X509EncodedKeySpec(ownerPubKeyBytes));
checkCreationTimeStamp();
} catch (InvalidKeySpecException | NoSuchAlgorithmException | NoSuchProviderException e) {
log.error("Couldn't create the pubkey", e);
}
}
public StoragePayload getStoragePayload() {
return storagePayload;
}