Commit Graph

393 Commits

Author SHA1 Message Date
catbref
964e0a02ca Fixes/improvements to networking
Reworked networking execute-produce-consume threading.
Some networking task were wrongly performed during 'produce' phase,
and some producing was happening in 'consume' phase (also corrected).

Peer connection tasks are rate-limited to 1 per second to reduce CPU thrashing.

Show P2P listen port in logs on startup.

Tests for general purpose ExecuteProduceConsume class to cover both
random task scenario and mass-ping scenario.
2019-08-13 08:40:50 +01:00
catbref
f8b496ff3c Convert SysTray to use JPopupMenu for Unicode support
Correct Systray_zh.properties to ISO 8859-1 instead of UTF-8.

Added SysTray test to GuiTests
2019-08-13 08:30:40 +01:00
catbref
82910b6524 Add periodic system-tray pop-up if Windows Time service not running 2019-08-13 08:27:43 +01:00
catbref
2f2d9a664d Replaced all NTP.getTime with System.currentTimeMillis. Clocks handled by O/S 2019-08-06 11:12:29 +01:00
catbref
9435e9576a Move getRewardByHeight from Block to BlockChain 2019-08-06 10:53:13 +01:00
catbref
e47b4dceb2 StringBuilder, and other, optimizations for repository-related classes.
Add optional "excludeZero" to API call GET /assets/balances

Added tests to call most API calls to check no exceptions are thrown.
2019-08-06 09:46:31 +01:00
catbref
48eae0cb38 Minor change to test account assertion message. 2019-08-06 09:41:52 +01:00
catbref
99ffd62a6e Change to how "best block" is determined. 2019-08-02 15:29:48 +01:00
catbref
915eebb8e5 BlockChain.isTestNet now BlockChain.isTestChain.
Added Settings.isTestNet.

Disabled ArbitraryDataManager for now.
2019-08-02 14:42:10 +01:00
catbref
2e6d33659c Fix CANCEL_ASSET_ORDER check for already closed, partially/fully matched, order.
Additional unit tests to cover above case.
2019-08-02 14:07:47 +01:00
catbref
d1d45b12f7 Added unit test to check initial proxy reward share of 0% is invalid 2019-08-02 13:06:16 +01:00
catbref
9af18aad34 Setting proxy forging reward share to 0% removes proxy forging relationship.
Included unit test to cover change.
Modified test blockchain config "test-chain-v2.json" to add maxProxyRelationships.

Added comments to some proxy-related methods in AccountRepository class.
2019-08-02 13:05:56 +01:00
catbref
03f60ef898 Fix incorrect declared transaction length for SET_GROUP and VOTE_ON_POLL transactions.
Added transaction [de]serialization test, along with corresponding random transaction generators.

Minor typo fix in Transaction.

Minor clarification in MessageTransactionTransformer.

Added debugging to Account.
2019-08-02 13:03:54 +01:00
catbref
02e8bdb034 Add support for fetching updates using a combination of hostname and IP address.
IP address used to create socket, hostname used for SNI, HTTPS, etc.

Added hostname+IP auto-update locations to Settings.
2019-08-02 12:53:49 +01:00
catbref
c2e8392f05 Synchronization improvements (again!)
Bumped version

Controller no longer uses block height to determine whether to sync
but now uses peer's latest block's timestamp and signature.

Also BlockGenerator checks whether it's generating in isolation using
the same peer info (latest block timestamp and signature).

Added API call POST /admin/forcesync peer-address to help get wayward
nodes back on track.

Unified code around, and calling, Transaction.importAsUnconfirmed().

Tidied code around somelock.tryLock() to be more readable.

Controller (post-sync) now broadcasts new chaintip info if
our latest block's signature has changed, not simply the height.

Network.broadcast() only sends out via outbound peer if node has
more than one connection from the same peer. So Controller would
only update one of the peer records with chaintip info.
Controller now updates all connected peers with the ID when it
receives a HEIGHT or HEIGHT_V2 message.

Added node1 thru node7.mcfamily.io to default peers in Network.

Network ignores first "listen port" entry when receiving peers
list from an outbound-connection peer as it already knows
by virtue of having connected to it!

More network message debug logging (hopefully never to be seen).

[some old code left in, but commented out, for a while]
2019-07-23 17:50:07 +01:00
catbref
e42c3e60bc Added mock-up of node management UI 2019-07-23 15:24:36 +01:00
catbref
4667b768df Added tests for each group-approval outcome + fixes 2019-07-23 15:13:28 +01:00
catbref
c9f226cf88 group approval tests and fixes 2019-07-23 15:12:35 +01:00
catbref
4b3f877dc0 Interim commit - refactored transaction transformers and fixed unit test compiler errors 2019-07-23 15:06:28 +01:00
catbref
06ba004238 Interim commit - refactored HSQLDBTransactionRepository, and subclasses. Also added approval_height to transactions, renaming height to block_height. 2019-07-23 14:50:56 +01:00
catbref
da1bd82c19 Minor integration progress
Remove fetching unconfirmed from Synchronizer

Add extra validity/reference/processable checks to
Transaction.isValidUnconfirmed

Update TransactionUtils to use Transaction.importAsUnconfirmed
for unit tests.
2019-07-23 14:48:49 +01:00
catbref
c9968b3dd2 Interim commit of *TransactionData classes for safety 2019-07-23 14:42:02 +01:00
catbref
c83d888a7d Demo HTML/JS page to show encrypted local storage of private key 2019-07-23 12:48:47 +01:00
catbref
f3c588d90f Fix sometimes erroneous Ed25519 public key to X25519 public key conversion.
Added mass (x1000) testing of key conversion and shared secret calculations.

Fix incorrect proxy private key test that has expected result from previous
algorithm.

Added another test HTML/JS file.
2019-07-23 11:22:23 +01:00
catbref
8f7c954f5a Proxy private keys are now SHA256(shared secret only) instead of SHA256(shared secret + public keys).
HTML/JS in src/test/resources/proxy-key-example.html updated accordingly.

Add handshake status to output of API call GET /peers

Add/correct @ApiErrors annotations on some API calls.

Add API call POST /admin/orphan (target height as body)
to force blockchain orphaning for when node is wildly out of sync.
Added support for above to BlockChain class.

BlockGenerator now requires a minimum number of peers
before it will generate any new blocks.
See "minBlockchainPeers" in settings.

Controller now requires a minimum number of peers
before it will consider synchronizing.
See "minBlockchainPeers" in settings.

Old "minPeers" entry in settings.json no longer valid!

Networking now allows both an outbound and inbound connection
to a peer although will use the outbound connection in preference.

Networking checks peer ID of inbound connections to detect,
and resolve, peer ID clashes/theft.
2019-07-23 11:09:25 +01:00
catbref
a3d4cf2900 MAJOR: Don't delete transactions when orphaning - make them unconfirmed again
Lots of edits to Transaction subclasses to change/remove 'delete'.

Corresponding extra changes to help reset some transaction fields to pre-process
state during orphaning.

Changed Block, GenesisBlock & Synchronizer to save transactions where appropriate.

Added enhanced GET_SIGNATURES_V2 network message to reduce the number of
block signatures sent over network.

Peers are now version 2 if they send a new-style build version string,
instead of using first digit from build version.
2019-07-23 10:37:37 +01:00
catbref
0259702df2 Fix generating X25519 shared secret.
X25519 shared secrets now match those generated by libsodium.

New tests show that shared secrets are the same using either set
of private+public key combinations.

Changed proxy private key generation from using simple SHA256
of shared secret to using SHA256(shared secret + both public keys).

Added a temporary "BouncyCastle25519" shim class to provide missing
key conversion from Ed25519 to X25519.
2019-07-23 10:29:18 +01:00
catbref
4279ad0673 Fix Javascript shared-secret & proxy forging private key code 2019-07-23 10:20:20 +01:00
catbref
4b02b7a14f Fix unit tests 2019-07-22 18:05:41 +01:00
catbref
57b982d2fb Block summaries (repository/data/message/synchronizer) + BlockGenerator
Also refactored some tests.

Original commit was 06fe8fc, with commit message:
Initial implementation of random block generator, etc.
2019-07-18 12:15:11 +01:00
catbref
a316b8a810 Potential HSQLDB deadlock fix
After opening repository connection with RepositoryManager.getRepostory(),
any 'read' from repository (e.g. SELECT) starts the transaction
even though HSQLDB documentation states there are no shared/read locks
in MVCC concurrency model.

The work-around for this is to 'reset' HSQLDB's in-transaction flag
by performing a ROLLBACK (Repository.discardChanges) immediately
after acquiring the blockchain lock (which is used to ringfence
changes that might collide like these).

Also adding an extra check to prevent payments to nonexistent AT
addresses as it touches Transaction.
2019-04-29 15:18:44 +01:00
catbref
d33ffee3ba Work on granting forging rights
Move hard-coded forging tiers to blockchain config.
Tests for granting forging rights.

Added API call to list top block forgers.

Fixed typo with Reward[s]ByHeight class name.
2019-04-19 09:55:04 +01:00
catbref
93230e9704 Add API call to list blocks with given generator. +more tests +pad genesis public key 2019-04-17 18:11:16 +01:00
catbref
d1c547f24a Refactor to use BouncyCastle Ed25519/X25519, and more...
Remove old whispersystems, etc. *25519 and use new v1.61 BouncyCastle.

Fix proxy forging private key derivation from X25519 shared secret.
Also include Javascript test version for comparison.

Fix block rewards for proxy forging.

Add extra useful info to API call GET /admin/forgingaccounts.
Fix API response to POST/DELETE /admin/forgingaccounts when
passed invalid private keys.

Added block rewards and account flags to testchain config.

Tests to cover changes above.
2019-04-17 12:32:03 +01:00
catbref
3c06d358b7 interim commit with proxy forging repository/transaction support
no block validity/generator support yet
2019-04-12 12:53:44 +01:00
catbref
2dc1720af8 Initial support for account flags + tx (genesis account use only atm) 2019-04-12 12:50:10 +01:00
catbref
85acc4d9df Fix incorrect refunds when cancelling asset orders
Also improved asset tests in that they don't use QORA any more
which takes fees/block rewards out of the picture.

More test assets are issued in the genesis block to
accomplish this:

1m TEST issued to Alice
1m OTHER issued to Bob
1m GOLD issued to Alice
2019-04-12 10:38:25 +01:00
catbref
2f51ced5c0 Fix incorrectly applied price improvement refund.
Also fix broken tests which contributed to this bug slipping by.
2019-04-12 08:44:13 +01:00
catbref
c23f55e6a6 Asset trading: refund saving due to price improvement back to initiator
Added test case to cover the above.

Also improve test harness to properly check balances after orphan back to genesis.
2019-04-11 17:47:12 +01:00
catbref
16dab6972c Fix some asset orders incorrectly matching worse prices. 2019-04-10 15:25:16 +01:00
catbref
a5e963911d New asset pricing scheme (take 2)
Orders are back to having "amount" and "price".
(No more "unitPrice" or "wantAmount").

Order "amount" is expressed in terms of asset with highest
assetID.
"price" is expressed in (lowest-assetID)/(highest-assetID).

Given an order with two assets, e.g. QORA (0) and GOLD (31),
"amount" is in GOLD (31), "price" is in QORA/GOLD (0/31).

Order's "fulfilled" is in the same asset as "amount".

Yet more tests and debugging.

For simplicity's sake, the change to HSQLDB repository is
assumed to take place when 'new' pricing switch also
occurs.

Don't forget to change "newAssetPricingTimestamp" in
blockchain config JSON file.
2019-04-10 07:18:50 +01:00
catbref
26e3adb92b Completing work on new asset trading changes
Changed API call GET /assets to NOT return asset "data" fields
as they can be huge. If need be, call GET /assets/info to fetch
a specific asset's data field.

Improve asset trade amount granularity, especially for indivisible
assets, under "new" pricing scheme only.

Added corresponding tests for granularity adjustments.

Fix/unify asset order logging text under "old" and "new"
pricing schemes.

Change asset order related API data models so that old "price" is
now "unitPrice" and add new "return" as in amount of want-asset
to receive if have-asset "amount" was fully matched.
(Affects OrderData, CreateAssetOrderTransactionData)

Some changes to the HSQLDB tables.

Don't forget to add "newAssetPricingTimestamp" to your blockchain config's
"featureTriggers" map.
2019-04-03 18:00:20 +01:00
catbref
60e562566e Interim commit on new asset trading schema
Better order matching, especially in situations
where inexact fractional representations (e.g. 1/12)
or rounding issues might occur. Also better matching
with indivisible assets.

Essentially change ordering from have-amount & price
to have-amount and want-return, leaving unit price
to be calculated internally to a finer degree (in
some cases to 48 decimal points).

Corresponding unit tests to cover both legacy and new
scenarios. Support for tests to switch between
blockchain configs.

"New" pricing schema is its own 'feature trigger'
independent from general qorav2 switch.

Safety checks added during trading process.

HSQLDB schema changes (will probably need
careful conflict resolution on merge).

Still to do:

API changes
etc.
2019-04-02 21:10:16 +01:00
catbref
789b311984 Interim commit with newer asset order "price" arg
+ unit test
+ newer unit test harness

but still needs:

BlockChain config support for activating newer "price" arg
New unit test to check old "price" arg usage

Rework existing asset-related unit tests

Check API inputs/output pre/post "price" arg crossover
2019-03-28 16:28:31 +00:00
catbref
870646fec8 Correct min/max block times for testing blockchain config 2019-03-26 14:32:51 +00:00
catbref
d53777f461 Added "data" field to assets, added UPDATE_ASSET tx + fixes 2019-03-13 14:06:52 +00:00
catbref
edcbf4f318 Add support for "only one registered name per account" + de-static brokenMD160 blockchain flag 2019-02-27 10:34:25 +00:00
catbref
16c1b13ab2 Proper JSON unmarshalling for settings, blockchain config, genesis block
GenesisBlock (v4) now supports various transaction types (issue-asset, etc.)
 with generated signatures (like genesis transaction signature) and
 missing references inserted.

JUnit reverted back to v4 for Eclipse support (for now).
2019-02-25 13:31:05 +00:00
catbref
86a35c3b71 Work on groups
Some dev/testing API calls are now turned off by default in production mode,
 see "restrictApi" settings entry, returning NON_PRODUCTION API error.

Corrections to how account's defaultGroupId works, removing "effective groupID"
 which overly complicated matters.
In relation to above, DEFAULT_GROUP (0) no longer exists and NO_GROUP(-1) now has
 the value 0 instead.
So transactions can no longer have txGroupId of DEFAULT_GROUP, which in turn
 required all the erroneous "effective groupID" code.

API call /addresses/{address} now supplies blockchain-wide defaultGroupId if
 account doesn't exist or if account's default not set and NO-GROUP not allowed.

API /transactions/pending now offloaded to repository instead of Java-based
 processing and filtering.

Transaction approval checks added to Block.isValid

Groups now have min/max approval block delays.
 Checks added to incoming unconfirmed, block generator, block.isValid, etc.

'needing approval' and 'meets approval threshold' now split into separate calls.

NB: settings.json no longer part of git repo
2019-02-20 12:25:30 +00:00
catbref
00656f6724 Interim safety commit due to large number of changes!
log4j2.properties now has debugging entries removed.
log4j2-test.properties (not in repo) takes priority
 so using that in development instead.

Unconfirmed transactions no longer wiped on start-up
 by default - see Settings

Reworking of {Public,Private,Genesis}Accounts as it seemed
 possible to silently lose public key in repository.
The use of AccountData didn't work and so field-specific
 repository calls have been made instead
 (e.g. setLastReference) that try to opportunistically
 store public key too, if available (i.e. caller is
 PublicKeyAccount subclass, or better).

Added API call GET /addresses/{address} to return
 general account info in one go. (Essentially the
 AccountData object as fetched from repository).

Initial work on adding default groupID to accounts,
 along with corresponding SET_GROUP transaction type.
In additional, added blockchain-wide default groupID
 and flag to allow/disallow no-group/groupless
 transactions.

Initial work on group-admin approval of transactions
 tied to a specific group via txGroupId.

More work needed on transaction's "effective txGroupId"!

API call /transactions/pending to list transactions
 pending group-admin approval. However, this needs more
 work (see effective txGroupId above) and potentially
 offloading to HSQLDB repository if possible.

Minor CIYAM AT renames to help static reflection initializers.

Block.orphan() no longer adds orphaned transactions back to
 unconfirmed pile as they are themselves deleted during
 Transaction.orphan(). Maybe the answer is to NOT delete
 them during Transaction.orphan() but to add them to
 unconfirmed pile at that point? Very old transactions
 leftover from major resync would simply expire, whereas
 recently transactions leftover from minor resync could
 still make it into a new block on synced chain fork.

Changes/tidying/improvements to block generator regarding
 removing invalid transactions and dealing with transactions
 pending group approval.

Approval threshold added to groups.

Mass refactoring of transaction-related classes to unify
 constructors, particularly field ordering, to fall in line
 with raw transaction layout.
e.g. constructors now reflect that raw transactions mostly
 start with type, timestamp, txGroupId, publicKey, reference
e.g. JAXB afterUnmarshal methods added where needed and corresponding
 nasty code in Transaction subclass constructors ripped out.
e.g. TransactionTransformer subclasses contain less duplicated code.

Fixed bug with repository save points thanks to swapping to Deque.

Some fixes to do with missing transaction types being passed to JAXB
 TransactionData subclass constructors.

Ripped out obsolete toJSON in TransactionTransformers as this
 is all nicely taken care of by Swagger/OpenAPI (thanks @Kc)
2019-02-18 19:00:37 +00:00
catbref
782bc2000f Added raw transaction layout API call to help build raw transactions.
Converted unwieldy tx-type switch statements to use reflection.
2019-01-17 09:01:05 +00:00
catbref
5c6e239d76 initial work towards OSGi
refactored packages so they all start with org.qora

added some attempt at OSGi mega bundle using Maven (doesn't work)
2019-01-04 10:19:33 +00:00
catbref
c4ed4b378c Refactoring, new translations, cleaning up warnings.
Refactored to standard Maven layout:
src/main/java
src/main/resources
src/test/java
etc.

New translation code that uses locale-specific ResourceBundles
to load translations on demand.

Reworked API error/exceptions code to a shorter, simpler
@ApiErrors annotation. Processing of @ApiErrors annotations
produces an example for each possible API error and includes
API error string in HTTP response code, e.g.
400 INVALID_SIGNATURE
Missing API error cases added to each API call.

Translation of openAPI.json removed (for now).

block-explorer.html and BIP39 wordlists now read as resources
instead of direct from disk.

Java compile warnings fixed.
Some runtime warnings remain:

WARNING: A provider api.resource.ApiDefinition registered in SERVER runtime does not implement any provider interfaces applicable in the SERVER runtime.
WARNING: A provider api.resource.AnnotationPostProcessor registered in SERVER runtime does not implement any provider interfaces applicable in the SERVER runtime.
WARN org.reflections.Reflections - given scan urls are empty. set urls in the configuration
2018-12-21 11:14:16 +00:00
catbref
eaad565765 Moved tests to outside of src/ path
This allows them to be excluded from final built package.

pom.xml and .classpath updated

Unable to test due to lack of JUnit 5 in Eclipse Neon
2018-11-02 15:52:09 +00:00
catbref
5526f9a7f0 More work on integrating CIYAM AT v2
Now using ATv2 dated 20181101172102

ATData now uses byte[] creatorPublicKey instead of String creator.

TransactionData now has hashCode() and equals() methods,
which is needed for new Transaction Comparator,
used to sort transactions within a block,
AT-first, then timestamp, then signature.

AT-Transactions generate their own signatures using SHA2-256 of serialized data.

Arbitrary Transactions try to clean up their files when orphaned.

Deploy AT Transactions now check creation bytes (even for old v1 ATs).

Deprecated Transaction.getBlock() as it doesn't seem used
and would be better to simply have getHeight() rather than
a method that 'knows too much' about Blocks/BlockData.
Corresponding TransactionRepository.getBlockDataFromSignature()
also deprecated.

Loads more comments.

Tidied up some SQL: mainly correcting case,
moving PRIMARY KEY clauses to end of CREATE TABLE,
removing unnecessary columns from indexes.

Added "type" column to TransactionCreatorIndex so users can find
their transactions and optionally filter by type.

In BlockTransactions table, transaction_signature is now UNIQUE
as a transaction cannot be included in more than one block.

Various AT-related HSQLDB table and index changes.

ArbitraryTransactions transformer fixed to always return a list of payments,
even if empty. (Previously could return null which broke things).

Added simplistic block generator.

NOTE: unit tests broken due to pending upgrade to JUnit 5
2018-11-02 10:30:51 +00:00
catbref
24ae771867
Merge branch 'master' into master 2018-10-31 09:40:27 +00:00
catbref
2c51a0362b Finally syncs with qora1 chain!
ATData no longer needs deploySignature as a link back to DeployATTransaction,
but does need creator and creation [timestamp].
"creation" is critical for ordering ATs when creating/validating blocks.

Similar changes to ATStateData, adding creation, stateHash (for quicker
comparison with blocks received over the network), and fees incurred
by running AT on that block.
Also added more explicit constructors for different scenarios.

BlockData upgraded from simplistic "atBytes" to use ATStateData (above)
which has details on ATs run for that block, fees incurred, and a hash
of the AT's state. atCount added to keep track of how many ATs ran.

ATTransactions essentially reuse the GenesisAccount's publickey as
creator/sender as they're brought into existence by the Qora code
rather than an end user. ATTransactionData updated to reflect this
and the AT's address used as a "sender" field.

Account tidied up with respect to CIYAM ATs and setConfirmedBalance
ensures there is a corresponding record in Accounts (DB table).

Account, and subclasses, don't need "throws DataException" on
constructor any more.

Fixed bug in Asset Order matching where the matching engine
would give up after first potential match instead of trying others.

Lots more work on CIYAM AT, albeit mainly blind importing of old
v1 ATs from static JSON file as they're all dead and new
v2 implementation is not backwards compatible.

More work on Blocks, mostly AT stuff, but also fork-based corruption
prevention using fix from Qora v1.

Payment-related transactions (multipayment, etc.) always expect/use
non-null (albeit maybe empty) list of PaymentData when validating,
processing or orphaning.
Mainly a change in HSQLDBTransactionRepository.getPayments()

Payment.isValid(byte[], PaymentData, BigDecimal, boolean isZeroAmountValid)
didn't pass on isZeroAmountValid to called method - whoops!

Lots of work on ATTransactions themselves.

MessageTransactions incorrectly assumed the optional payment was always
in Qora. Now fixed to use the transaction's provided assetId.

Mass of fixes/additions to HSQLDBATRepository, especially fixing
incorrect reference to Assets DB table!

In HSQLDBDatabaseUpdates, bump QoraAmount type from DECIMAL(19,8)
to DECIMAL(27,8) to allow for huge asset quantities.
You WILL have to rebuild your database!
2018-10-26 17:47:47 +01:00
Kc
af84cc8575 CHANGED: simplified AssertExtensions 2018-10-10 00:16:02 +02:00
Kc
730b5033d1 CHANGED: switched to JUnit5
CHANGED: globalization tests
2018-10-04 22:58:04 +02:00
Kc
d24f1de36a CHANGED: added translation context path normalization 2018-10-04 16:36:45 +02:00
Kc
6bc0eeac4d ADDED: TranslationXmlStreamReader + tests for XML based translation files 2018-10-04 16:36:45 +02:00
catbref
e9d8b3e6e3 Unit test fixes + initial CIYAM AT integration
NB: we're still using HSQLDB svn r5836

Updated README.md

Added log4j2.properties file for logging!

Imported CIYAM-AT jar into project-local Maven repo
CIYAM-AT related:
ATData
ATStateData
ATTransactionData
DeployATTransactionData
AT
DeployATTransaction
ATRepository
HSQLDBATRepository
HSQLDBDeployATTransactionRepository
ATTests
DeployATTransactionTransformer

Fixed Block so correct block hash and timestamps are generated,
especially when previous/next block versions differ.
Added extra call in BlockTransformer to aid this.

Fixed GenesisTransaction.isValid's incorrect amount test.

Fixed comments in TransferAssetTransaction and incorrect use of BlockChain.getVotingReleaseTimestamp()
instead of BlockChain.getAssetsReleaseTimestamp().

Added new TYPEs to HSQLDBDatabaseUpdates, and set LOB granularity to 1KB for AT use.
Added AT_address column to DeployATTransactions in HSQLDB.
Added ATs, ATStates and ATTransactions tables.
(You will need to discard existing database and rebuild).

Fixed incorrect byte array output in IssueAssetTransactionTransformer,
where Asset "references" were not processed correctly.

Added support for BigDecimal serialization to a byte-array size other than the standard 8.
2018-10-04 14:38:59 +01:00
catbref
e56d8f5e02 HSQLDB issue, resource leak prevention, v1 differences
HSQLDB v2.4.0 had some issue with non-padded, case-insensitive string comparisons.
This is fixed in svn r5836-ish of HSQLDB but yet to be pushed out to new HSQLDB release.
So this commit includes hsqldb-r5836.jar and modified pom.xml/.classpath for now.

No need for duplicate, hidden creatorPublicKey in CancelOrderTransactionData,
CreateOrderTransactionData and CreatePollTransactionData.

Various changes to use more try-with-resources, especially with JDBC objects like
Connection, Statement, PreparedStatement, ResultSet.

Added loads of missing @Override annotations.

Fixed bug in Asset exchange order matching where the matching logic loop
would incorrectly adjust temporary amount fulfilled
by the "want" asset amount (in matchedAmount)
instead of the "have" asset amount (in tradePrice).

Disabled check for duplicate asset name in IssueAssetTransactions for old v1 transactions.

In HSQLDB repository we now use ResultSet.getTimestamp(index, UTC-calendar) to make sure we
only store/fetch UTC timestamps. The UTC-calendar is made using static final TimeZone called
HSQLDBRepository.UTC.

To keep asset IDs in line with v1, Assets.asset_id values are generated on-the-fly in HSQLDB
using a "before insert" trigger on Assets table. Corresponding code
calling HSQLDBRepository.callIdentity() replaced with SELECT statement instead.

Moved most of the HSQLDB connection properties from the connection URL to explicit code in
HSQLDBRepositoryFactory.

Fixed incorrect 'amount' lengths in PaymentTransformer, as used by MultiPayment and Arbitrary
transaction types.

Added support for mangled arbitrary transaction bytes when generating/verifying a v1 transaction signature.
In v1 Arbitrary transactions, bytes-for-signing are lost prior to final payment (but only if there are any payments).
Added corresponding code for multi-payment transactions in the same vein.
2018-08-07 15:44:41 +01:00
catbref
7da84b2b85 Arbitrary Transaction support + various fixes
NOTE: requires HSQLDB built from svn rev 5836 or later

Fixed BuyNameTransactionData constructors not picking up nameReference.

Added new "orphan" tool to regress blockchain back to specified block.

Added new Block constructor for when receiving a block from the network.
Fixed Block generatingBalance/forging code to be compliant with v1.
Added logging of transactions that fail validation during block validation.

Fixed buyer/seller balances not being updated during name purchase.

Generally replace BigDecimal.compareTo expressions with "<operator> 0" form.
e.g. instead of someBigDecimal.compareTo(anotherBigDecimal) == 1
we now have someBigDecimal.compareTo(anotherBigDecimal) > 0

Fix amounts involved in BuyNameTransactions.

Renamed Transaction.calcSignature to .sign

Refactored Transaction.toBytesLessSignature to TransactionTransformer.toBytesForSigning,
which itself calls subclass' toBytesForSigningImpl,
which might override Transaction.toBytesForSigningImpl when special v1 mangling is required.

Corrected more cases of NTP.getTime in transaction processing
which should really be transaction's timestmap instead.

Fixed HSQLDB-related issue where strings were padded with spaces during comparison.
Some column types no longer case-insensitive as that mode of comparison
is done during transaction validation.

Added missing option_index column to CreatePollTransactionOptions which was causing
out-of-order options during fetching from repository and hence signature failures.

Added unit tests for v1-special mangled transaction signature checking.

Removed checks for remaining bytes to ByteBuffer in various transaction transformers'
fromByteBuffer() methods as the buffer underflow exception is now caught in
TransactionTransformer.fromBytes.

Corrected byte-related transformations of CreatePollTransactions that were missing
voter counts (albeit always zero).

Corrected byte-related transformations of IssueAssetTransactions that were missing
duplicate signature/reference (v1-special).

Added "txhex" tool to output transaction in hex form, given base58 tx signature.

Added "v1feeder" tool to fetch blocks from v1 node and process them.
2018-08-02 10:02:33 +01:00
catbref
b401adcc55 Added asset order matching support.
Added isFulfilled property to asset orders so completed orders can be filtered out.

Fixed migrate app by adding dummy name_reference values to UpdateNameTransactions and BuyNameTransactions INSERTS.
Fixed migrate app to use "poll_name" instead of "poll" for column name. Ditto "option_name" instead of "option".

Fixed some other incorrect column names in HSQLDBAssetRepository.

More unit tests but probably need yet more to cover complicated asset order matching with various divisibility settings.
Maybe fuzzing would help here somehow?
2018-07-05 16:24:05 +01:00
catbref
104be89b4e Added MultiPaymentTransaction test 2018-07-04 13:53:20 +01:00
catbref
7536ab37fa More tests and fixes resulting from such
Settings class reworked to allow easier testing

Fix to Payment.orphan() where fee was being incorrectly subtracted instead of added

Added AssetRepository.fromAssetName(String): AssetData

Fixed deleting assets from HSQLDB repository due to broken column name in SQL.

Fixed saving IssueAssetTransactions in HSQLDB repository due to missing column binding.

More TransactionTests!
2018-07-04 12:49:56 +01:00
catbref
2bfb0227ae Added BuyNameTransaction support
Fixed IssueAssetTransactions not being constructed with signature.
Fixed incorrect MessageTransactionData constructors.

Refactored various transactions to remove duplicate code.
e.g. in CancelOrderTransaction.process() use getCreator() instead of explicit repository call.

Added name_reference to BuyNameTransactions HSQLDB table.

Fixed incorrect SQL in HSQLDBMultiPaymentTransactionRepository.

More unit tests!

Fixed wrong data length in CancelOrderTransactionTransformer.
Fixed wrong data length in CreateOrderTransactionTransformer.

Fixed missing payment bytes in MultiPaymentTransactionTransformer.toBytes();
2018-07-03 11:40:24 +01:00
catbref
c8be77e7cc Added CancelNameSaleTransactions + fixed dodgy UTF-8 [d]serialization/getDataLength() 2018-07-02 18:59:11 +01:00
catbref
0fc17d76ae Added SellNameTransactions + tests 2018-07-02 18:09:36 +01:00
catbref
c79bec90bc Added UpdateNameTransaction
* Added more columns/properties to NameData to support updating timestamps, name sales
and reference to last transaction that changed Name (for orphaning support).

* Fixed serialization/deserialization bugs in MessageTransactions

* More tests
2018-07-01 16:35:45 +01:00
catbref
4de2caaa28 Added RegisterNameTransactions
Fixed CreatePollTransaction transformer bugs
2018-07-01 09:34:57 +01:00
catbref
70d25f24ce Fix deleting rows from HSQLDB repository & improve transaction tests 2018-06-29 11:05:15 +01:00
catbref
fe6cb4e366 Added Vote-on-poll transaction
* Added simple genesis block timestamp setting to help testing

* Fixed setting account's last reference

* Moved some Poll constants from CreatePollTransaction to Poll

* HSQLDB: added TYPE PollOptionIndex
* HSQLDB: added previous_option_index to VoteOnPollTransactions table to help orphaning
* HSQLDB: renamed "poll" to "poll_name" in same table
* HSQLDB: PollOptions now has additional option_index column

* Improved TransactionTests to allow for different genesis block timestamps.
* Also added VoteOnPollTransaction test
2018-06-29 10:29:18 +01:00
catbref
05e0fd92b9 Work on Polls
Added CreatePollTransactionData constructor that doesn't need signature (for creating new transactions).

Added missing "published" timestamp support to PollData and Poll.

Removed extraneous timestamp test from Block.isValid.

Corrected inconsistent column names in poll-related tables in HSQLDBDatabaseUpdates.

HSQLDBRepository.checkedExecute(PreparedStatement) now takes extra Object... params
so that values can be bound to placeholders. Code moved from checkedExecute(String, Object...).
This fixes an issue with exists(String, String, Object...) where placeholders weren't having
any values bound to them. (Also removed "ORDER BY NULL" clause which isn't supported by HSQLDB).

HSQLDBVotingRepository method stubs fleshed out with real code.

TransactionTests rejigged but more work needed to test various transactions before/after their feature
release. e.g. testing create poll transactions before & after they supposedly went live.

Could do with a GenesisBlock constructor that takes a timestamp for testing purposes?

CreatePollTransactionTransformer now skips serializing a null signature,
in the same way PaymentTransactionTransformer does, to aid getBytesLessSignature().
This will probably need to be rolled out to all other transaction types.
2018-06-21 12:38:45 +01:00
catbref
c5a32ffa1c Block/Transaction processing
* Add implementation for Account.getBalance(assetId, numberOfConfirmations)

* Added orphan() code to Block (CIYAM AT not yet supported)

* Added getOrder() 'navigation' method to CreateOrderTransaction

* Added missing transaction-type cases to various switches in Transaction, transformers, repositories, etc.

* Various repository delete() methods added

* Added save/delete support for transaction types that include payments, like multipayment and arbitrary

* Changed "recipient" in HSQLDB SharedTransactionPayments from QoraPublicKey to QoraAddress
2018-06-19 09:50:58 +01:00
catbref
4a1c3821db Progess on block and transaction processing + tidying up
* Code added for calculating an account's generating balance. (CIYAM AT support yet to be added).
* Added associated code in Block for calculating next block's timestamp, generating balance, base target, etc.

* ValidationResult enum added to Block, mostly to aid debugging.
* Block.isValid() now returns ValidationResult instead of boolean.
* Block.isValid() now has added proof-of-stake tests.

* Some blockchain-related constants, like feature release heights/timestamps, moved from Block to BlockChain.

* Added better Block constructor for use when creating a new block.
* Added helpful 'navigation' methods to Block to get to block's parent (or child).

* Changed visibility of block's individual signature calculators to protected, in favour of public sign() method.

* Added asset existence check to Payment.isValid.

* All current transaction objects (qora.transaction.*) now have private subclassed transaction variable to save multiple casts in various methods.
* Also added to above:
* isInvolved(Account) : boolean
* getRecipients() : List<Account>
* getAmount(Account) : BigDecimal

* Added BlockRepository.getLastBlock() to fetch highest block in blockchain.

* Added diagnostics to HSQLDBRepository.close() to alert if there are any uncommitted changes during closure.
(Currently under suspicion due to possible HSQLDB bug!)

* Old "TransactionTests" renamed to "SerializationTests" as that's what they really are.

* New "TransactionTests" added to test processing of transactions. (Currently only a PaymentTransaction).

* PaymentTransformer.toBytes() detects and skips null signature. This was causing issues with Transaction.toBytesLessSignature().
Needs rolling out to other transaction types if acceptable.
2018-06-15 17:16:44 +01:00
catbref
2c23acfa74 Fix HSQLDB*Transaction save() methods
Added RepositoryManager.closeRepositoryFactory() to allow swapping out of repositories during unit testing

Added some more unit tests - all pass!
2018-06-14 09:55:58 +01:00
catbref
4c18c7c5bc Fix unit test failures - mostly to due with [de]serialization bugs 2018-06-14 09:03:12 +01:00
catbref
c25ccc064f Surround RepositoryManager.getRepository() calls within try-with-resources 2018-06-13 17:46:51 +01:00
catbref
fc3e951e8e Renamed and converted unit tests **COMPILES OK BUT UNTESTED**
Let the debugging begin!
2018-06-13 16:48:28 +01:00
catbref
3d78d5dad9 More refactoring - DOES NOT COMPILE
qora.* packages are business logic/handler/processing
data.* packages are "value objects" or are they "business objects"?

toBytes(), fromBytes() (which used to be called parse()) and toJSON() moved to transform.* packages

new issues:

Lost control of SQL Transactions. Previously, some class "knew" whether to call COMMIT or not.
e.g. simply saving a payment transaction would involve updating Transactions table first, then the PaymentTransactions table after (to satisfy foreign key constraints) then commit.
Processing a block would involve a new transaction, a savepoint, a rollback and then maybe a further commit or rollback.
Not sure how this is going to work with the repository, especially if business logic isn't supposed to be aware of such things.

Growing number of stupid try-catch blocks. Probably best to ditch TransformationException (was ParseException) and throw IllegalStateExceptions instead as they're "unchecked".

What happens if the repository fails to save() to the database? It can't throw SQLException any more as that has no meaning outside the repository. Ditto with delete().
2018-06-08 17:40:27 +01:00
catbref
5b78268915 Convertion to thread-local Connection
Much tidier code thanks to not having to pass Connection objects around
as params. Also no need for two forms of the same method, one with Connection
param, one without.

Also corrected SQL-Transaction-related methods in DB, e.g. commit, rollback, etc.
so they use the proper underlying JDBC methods.
2018-06-06 11:39:58 +01:00
catbref
3a6276c4a9 IssueAssetTransactions
Use HSQLDB "CREATE TYPE" instead of "CREATE DOMAIN" as collate clause is lost on HSQLDB shutdown in v2.4.0.

Restore GenesisAccount's public key back to 8-byte legacy value.

More work on block/transaction processing.

It's becoming apparent that way too many Connection objects are being passed around, and now with two forms of
methods (one with, one without) it's time to switch to something like thread-local Connections.

Maybe also switch to having data access objects.

So this commit is save work prior to that conversion.
2018-06-06 09:52:42 +01:00
catbref
948bc95644 More work on transactions/blocks
Added Apache commons-net as maven dependency for NTP support.

Added SAVEPOINT and ROLLBACK TO SAVEPOINT support to DB class.
Added exists() test to DB class.

Add MessageTransactions, with V1/V3 code in one class instead of very similar code
split across two classes. Update DB schema to add version.

More fleshing out of Assets class.

Fleshing out Block class with parse(), generating balance and signature-related methods.

More javadoc. More tests.
2018-06-04 11:45:40 +01:00
catbref
4ce499c444 More database work
No need for DB.executeUsingBytes as it was only a specific use-case for DB.checkedExecute.
Callers now refactored to use DB.checkedExecute instead.
Minor tidying up of BlockTransactions in light of above.

In the HSQLDB database, asset keys/IDs are now "asset_id" (previously: "asset").
Added initial Asset/Order/Trade classes.
Added CreateOrderTransaction class.
Renamed some asset-related fields back to old gen1 names, e.g. haveAmount -> amount, wantAmount -> price.

Added Accounts and AccountBalances to database.

Added get/set confirmed balance support to Account.
Added get/set last reference support to Account.

Added Block.toJSON() - untested at this time.

Fleshed out some Transaction sub-classes' process() and orphan() methods.
Fleshed out PaymentTransaction.isValid().
Added Transaction.delete() - untested.
2018-05-27 14:59:30 +01:00
catbref
63be6b7e90 Basic block and genesis transaction processing + some refactoring.
DB.rebuild() to shutdown and delete database, then rebuild it (schema only).

DB.callIdentity() to fetch value of IDENTITY column after an INSERT.

Added basic Asset class.

Added TODOs to Account.

BULK REFACTOR to rename "generation target" back to "generating balance" and
"generation signature" back to "generator signature" to ease compatibility with
old QORA for now. (Maybe change again in the future if we change from PoS).

Added support for Block's totalFees which is either loaded from DB
or recalculated as transactions are added to the block.

Also in Block:

* We can't assume generator's public key is the correct length
in case we encounter the GenesisAccount's special 8-byte public key. Fix applied to
Block's ResultSet-based constructor.

* Forgot to save "signature" column!

* Initial version of Block.process()

* Block constructor takes transactionsSignature too now

Added BlockChain startup/init/validation method to determine whether to (re)build blockchain.
Rebuilding blockchain involves rebuilding DB schema, processing GenesisBlock and adding QORA asset.

Added some initial GenesisTranaction.process() code: GenesisTransactions are saved but recipient's balance/reference not yet updated.

Fix incorrect placeholder bind value for "creation" timestamp in Transaction.save().

Moved incremental database schema updates out from "updates" unit test into DatabaseUpdates class.

All unit tests work at this point!
2018-05-25 11:48:47 +01:00
catbref
c8167248fc whitespace fixes 2018-05-24 21:12:24 +01:00
catbref
387c18c909 Some serialization
Add Transaction.parse() support. Subclasses are called, switched by transaction type,
using ByteBuffer.

Correct RECIPIENT_LENGTH in Transaction.

Common [de]serialization tasks moved to methods in Serialization class.
2018-05-24 21:08:21 +01:00
catbref
015f4fa725 Rework DB connection arg passing
Too many calls needing Connection object in args when they're only
simple database reads. Even worse, some methods had database-less
counterparts with different outputs, e.g. toJSON().

Now Connections can be requested from the pool for general database
read scenarios. Code paths that might perform a multi-statement
database transaction still require a Connection arg passed around
as the database transaction are local to that Connection.

In light of above, added support for database opening, closing,
setting URL.

Fixed out of bounds array index bug in unknown-length version of DB.getResultSetBytes().

Fixed Block's lazy-instantiation of Transactions.
Implemented Block's isSignatureValid().

Fixed bug in Crypto.isValidAddress() which was using the wrong bytes.

Fix GenesisTransaction generic constructor calling super with PaymentTransaction type!
Fix GenesisTransaction signature constructor using wrong column indexes from ResultSet.

In Transaction, don't expect CREATOR_LENGTH bytes from database in case we're dealing
with a GenesisTransaction where the creator's public key is only 8 bytes long.

Improvements to unit tests, including changing migrate so it can be run repeatedly to do
incremental migrations.
2018-05-24 11:26:59 +01:00
catbref
71f9d5c0f0 More work on transactions and blocks
PaymentTransaction now uses Account for recipient internally but maybe should extend that type change to constructor args.

GenesisBlock added also with signature test.

More javadocs.
2018-05-18 18:54:52 +01:00
catbref
b90a486039 More work on Blocks, refactor to using public key in DB, etc.
Added brokenmd160.java as command-line support for producing broken MD160 digests.

Transactions, and sub-classes, now use/store public key instead of Qora address.
(Qora address can be derived from public key and they take up about the same space in DB).

Loads more JavaDoc for lovely mouseover help in Eclipse IDE.

Crypto.verify() and Crypto.sign() moved into PublicKeyAccount and PrivateKeyAccount
as appropriate.

Fleshed out Block, added BlockTransactions support.

Added TODO comments as Eclipse helpfully lists these for later implementation.

Made loading-from-DB-constructors protected/private and also throw NoDataFoundException
if unable to load from DB. Public methods can call respective constructors, catch the above
exception and return null if they like. Load-from-DB-constructors are to allow sub-classes
to load some data from sub-tables and super-class to load from another table.
(See PaymentTransaction/Transaction for example). Using public methods allows similar argument
lists but with different names,
e.g. DBObject.fromSignature(Connection, byte[]) and DBObject.fromReference(Connection, byte[])

Saving into DB maybe still a bit untidy. Looking for a way to close-couple column names with
place-holder bind Objects.
Less of:
connection.prepareStatement("INSERT INTO table (column) VALUES (?)")
DB.bindInsertPlaceholders(PreparedStatement, Object...);
More like:
DB.insertUpdate(String tableName, SomeMagicCloseCoupledPairs...)
called like:
DB.insertUpdate("Cats", {"name", "Tiddles"}, {"age", 3});
2018-05-17 17:39:55 +01:00
catbref
a2b5fa140b Initial stab at migrating to HSQLDB for Qora gen2
Most SQL tables defined but only payment transactions actually implemented.
Maven support added.

Some code imported from 'old' Qora:

RIPEMD160 renamed as BrokenMD160 and deprecated.
whispersystem's Ed25519 implementation (to be replaced with bouncycastle).
Basic Account/PublicKeyAccount/PrivateKeyAccount code.
Some utils like Base58 and Pair.

To use:

Use maven to fetch dependencies.
Build project.
Fire up an old-gen Qora node.
Run src/test/update.java as a JUnit test to build DB structure.
Run src/test/migrate.java as a JUnit test to migrate old Qora blocks to DB.

You should now be able to run src/test/load.java and src/test/save.java
as JUnit tests demonstrating loading/saving Transactions from/to database.

This commit done while halfway through adding Block support!
2018-05-16 11:46:44 +01:00