Commit Graph

276 Commits

Author SHA1 Message Date
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
6a10df85ab Hide internal-use references from some objects emitted by API 2019-01-16 15:46:35 +00:00
catbref
c81a3838fc Added API call to list registered names that are for sale 2019-01-16 15:37:18 +00:00
catbref
e04f9df0dc Groups API: get invites by group ID or invitee
+ fixed API response models that were incorrectly NOT arrays
2019-01-16 15:22:15 +00:00
catbref
bc4de8f063 Groups: refactored to use group ID, not group name, plus fixes, etc. 2019-01-16 15:00:25 +00:00
catbref
3b4c12da56 Group ban/unban & pre-conversion to groupID & pre-tidy/refactor 2019-01-15 14:41:36 +00:00
catbref
90f1676c7c Account group invite/cancel-invite and kick
Account group join for a group that is closed/invite-only
and has no corresponding invite is now turned into a "join request".
This can be accepted by an admin sending a corresponding invite tx.
2019-01-14 14:36:43 +00:00
catbref
df730d9fb9 Add/remove account group admins (by owner) 2019-01-11 14:07:16 +00:00
catbref
02a620d57b Join/Leave account groups + API calls 2019-01-11 10:42:42 +00:00
catbref
760cb6cd37 JOIN Group + improved specific group info from API 2019-01-10 17:28:13 +00:00
catbref
83abede8ab Account groups: create group + update group + API calls
(Also minor fix for orphan.java).

Note use of afterUnmarshal() in TransactionData-subclass to replace trash code in Transaction-subclass constructor.
See UpdateGroupTransactionData.afterUnmarshal() compared to RegisterNameTransaction constructor.
2019-01-10 15:45:00 +00:00
catbref
74bf930698 API: added support for sell, cancel-sell and buy name transaction builders 2019-01-09 16:03:07 +00:00
catbref
22c87a6e08 API + fix for names in HSQLDB
Added POST /names/update for building an UPDATE-NAME transaction.

BlockGenerator now tries to validate new block after adding each
unconfirmed transaction in turn. If block becomes invalid then
that transaction is removed/skipped. This should further prevent
block jams. Skipped transactions might be deleted as the next block
is forged when unconfirmed transactions are collated/filtered/expired.

Add Block.deleteTransaction() for use during block generation above.

Block.addTransaction() and Block.deleteTransaction() use transaction
signatures to test for presence in Block's existing transactions.

Names shouldn't have stored registrant's public key!
"registrantPublicKey" removed from NameData Java object/bean.
Corresponding column removed from HSQLDB using ALTER TABLE but
also from the original CREATE TABLE definition. Remove the ALTER
TABLE statement just prior to rebuilding database!

(This needs to be applied to Polls too as some point).

Also, UpdateNameTransactions and BuyNameTransactions tables now
allow name_reference to be NULL as this column value isn't set
until the corresponding transactions are processed/added to a
block. (name_reference is a link to previous name-related
transaction that altered Name data like "owner" or "data" so
that name-related transactions can be orphaned/undone).
2019-01-09 14:41:49 +00:00
catbref
95d640cc8c API + new tx restrictions
Added GET /names to list all registered name.
Added GET /names/{name} for more info on a specific name.
Added GET /names/address/{address} for names owned by address.

Renamed GET /assets/all to GET /assets in line with above.

Fixed edge cases with AnnotationPostProcessor.

Fixed incorrectly exposed "blockHeight" in API UI examples/values.
Changed example transaction timestamp.

Added checks on building/signing/processing new transactions via API
so that they are not too old (older than latest block's timestamp),
too new (more than 24 hours in the future) or the tx creator doesn't
already have a lot of existing unconfirmed transactions (default 100).

Configurable via settings.json properties maxUnconfirmedPerAccount
and maxTransactionTimestampFuture.

Improved /transactions/search to not return unconfirmed transactions
and to order by timestamp.

Transaction.getCreator() now returns PublicKeyAccount, not Account.
2019-01-08 17:30:23 +00:00
catbref
7998166c0a API, switchable MD160,
Now uses working RIPE-MD160 by default but can be switched to broken MD160 using flag in blockchain config,
e.g. for Qora v1 blockchain.

Replaced API signature/reference examples with descriptive text as they weren't very useful.
Replaced API address examples with ones generated using working MD160.

Added GET /transactions/signature/{signature}/raw that returns raw transaction in base58 encoding.

Added "ignoreValidityChecks" query param to POST /transactions/decode to bypass INVALID_REFERENCE errors
if supplying an old/speculative transaction that can't be added to unconfirmed transaction pile.

Finally fixed creating inital assets in BlockChain.

Controller now inserts BouncyCastle as highest priority Security Provider.

TransactionData & transaction repository now tries to return transaction's block height in data when possible.
2019-01-07 13:12:42 +00:00
catbref
b2ca63ce88 Add cancel order and get orders by address API support.
Added getAccountsOrders asset repository call to facilitate the above.
2019-01-07 09:31:27 +00:00
catbref
2497ac256c Added API call for creating an asset bid/ask order
Also added test for missing creator public key on API-submitted
transaction creation calls, like /payments/pay or /asset/issue.
(Needs to be an OpenAPI validator added at some point).
2019-01-04 19:10:50 +00:00
catbref
17f3958ad6 Fix ApiService to use new org.qora.* package names
Also add missing default for blockchain config file to Settings
2019-01-04 16:00:37 +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
9e425d3877 Clean unconfirmed transactions
Invalid/expired unconfirmed transactions are cleaned during various calls,
e.g. requesting list of unconfirmed transactions,
or requesting account's last reference (including considering unconfirmed),
or generating a new block.

BlockGenerator now calls repository.discardChanges before sleep to
release any repository-level locks.

Added settings.json toggle "wipeUnconfirmedOnStart" (default: true)
to aid testing.

REMOVED API call /addresses/lastreference/{address}/unconfirmed as
/addresses/lastreference/{address} now considers unconfirmed
transactions regardless.

Added useful error to /transactions/sign if an invalid private key
is supplied.

Improved API "invalid transaction" error to include actual apsect
that caused validity check to fail (e.g. invalid reference)
2018-12-28 16:37:59 +00:00
catbref
783edb3447 Wipe unconfirmed transactions on startup
Fix issues with last reference and unconfirmed transactions.
2018-12-21 15:27:38 +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
aab6b69da1 API: payments, issue asset, transaction decode, etc.
Added slow query check to HSQLDB repository to help
isolate cases where transaction searching takes too long.

Added BigDecimalTypeAdapter for normalizing API inputs
but doesn't seem to get reliably called so also added
.setScale(8) to BigDecimal serialization method.

API-built transactions are now validated before emitting
base58 raw transaction to help callers.

API's transaction decoder accepts signed/unsigned raw transactions.
2018-12-19 09:52:42 +00:00
catbref
107ef93b37 added API support for signing and processing transactions 2018-12-17 17:22:05 +00:00
catbref
963e4c5d35 spawn block generator thread from controller 2018-12-17 14:53:46 +00:00
catbref
999e6b7289 fix incorrect checksum test on bip39 mnemonic decoding 2018-12-17 14:33:33 +00:00
catbref
3045841151 added block timestamp too-soon check and relaxed PoS for too-old blocks 2018-12-17 14:18:23 +00:00
catbref
f50b53a407 Blockchain config (ncluding genesis block) moved out into config file 2018-12-17 13:28:37 +00:00
catbref
68f99cfc11 API: terminology corrections and more utility calls 2018-12-14 13:39:17 +00:00
catbref
e1dbaa5597 BIP39 seed phrase support 2018-12-14 11:26:38 +00:00
catbref
3ec3c69447 API: wholesale conversion back to Base58
XmlJavaTypeAdapter api.Base58TypeAdapter converts byte[] to Base58.
This XmlAdapter is applied at package-level to all packages inside data and api.models.
So no need to annotate every byte[] property!
Added package-info-maven-plugin to pom.xml to do this.

block-explorer.html fixed to show/use base58 again

Some data objects (e.g. TransactionData) have added XmlElements that
convert public keys to addresses, for convenience.

Several API calls updated to return specifically text/plain instead
of ambiguous application/json and/or text/plain. (Typically
API calls that return a single value, e.g. an integer, like /blocks/height).
2018-12-13 17:25:47 +00:00
catbref
034cf5dee3 API: assets & tidying
Cleaned up responses from /addresses/* endpoints
in that some return text/plain instead of application/json.

Removed need for class-local copy of ApiErrorFactory in
AddressesResource - using getInstance() instead.

Some work still needs to be done on annotating API errors.
API error examples in API UI rendered incorrectly - swagger-ui issue?

Removed repository-accessing code from api.models.*

Added /assets/order/{orderId} for fetching info on specific asset order.

NOTE: AssetRepository.getOrdersTrades() now returns trades where order is
initiating or target. (Previously was initiating order only).
qora.assets.Order.orphan() updated to reflect above change.

block-explorer.html fixed to use new API output.
2018-12-13 12:22:46 +00:00
catbref
dcd19f8e42 Transaction-specific info in API results 2018-12-13 08:44:50 +00:00
catbref
cfd8b53fc1 API, HSQLDB
Added more global parameters to /admin/unused API endpoint (formally /admin/dud)
and also managed to remove /admin/unused from API documentation UI.

Added results slicing to /assets/all

Added /assets/orderbook API call that returns open asset orders

Added /assets/trades that returns successful asset trades

Added POST /assets/issue stub

Unified HSQLDB connectionUrl to public variable inside Controller class.

Can't deploy v1 ATs with isFinished=true flag as that prevents later
transactions sending messages (during import of v1 chain).
Some future hard-fork code will need to set all v1 ATs to "finished".

Changed DB's "TransactionRecipients" to "TransactionParticipants" to
properly support API call to find all transactions 'involving' a
specific address. Support code needed in Block and Transaction with
some transaction-specific overrides for Genesis and AT transactions.

Removed old, deprecated calls from Transaction/TransactionRepository

Moved HSQLDB database properties from connection URL to explicit
SQL statements in HSQLDBDatabaseUpdates. They didn't work in
connection URL during DB creation anyway.

Retrofitted HSQLDB Accounts table with public_key column instead of
rebuilding it later.

Fixed incorrect comments in IssueAssetTransactionTransformer regarding
v1 serialization for signing.

Re-imported v1 chain to test latest changes.
2018-12-12 12:13:06 +00:00
catbref
2aaa199c86 API: basic asset info
Added repository support for asset API calls

Added /utils/seed for returning server-generated 32-byte seed
2018-12-11 13:48:10 +00:00
catbref
3829630b29 API: transaction searching
Converted AddressesResource to full base64, removing base58.
Narrowed range of API errors returnable while there.
Added support for looking up public key of address.
Added support for converting public key TO address.

Added API endpoint for returning a range of block signatures,
to aid block explorers.

Added API support for fetching unconfirmed transactions.
Added API endpoint for searching transactions to meet criteria like:
- participating address (only recipients supported ATM)
- block height range
- transaction type
- result count limit/offset

---

Added storage of account's public key in repository
along with supporting code in AccountData and Account
business object to save public key where possible.
2018-12-10 13:27:41 +00:00
catbref
b5c02f49ce Work on API
Rejigged pom.xml, extracting common dependency versions as properties.
Removed extraneous HSQLDB dependency (v2.4.1) as we're using svn r5836 for now.

Removed calls to Security.checkApiCallAllowed() for all API calls EXCEPT /admin/stop.
Throws error if remote IP is not localhost.

Added 'global' OpenAPI parameters to fake /admin/dud endpoint to save copy&pasting.
This will need more tidying in the future, or at least future support from swagger-core.
Code added in AnnotationPostProcessor to insert global parameters in top-level
  OpenAPI components section.

/block-explorer.html hidden from API UI

BlocksResource now expects Base64 block signatures instead of Base58.
Endpoints that return block data also accept optional "includeTransactions"
    query param which does exactly that.
BlockWithTransactions API model added for above.

Some attempt to get transaction-specific data returned but no luck as yet.
(TransactionData, GenesisTransactionData, PaymentTransactionData touched).
See https://github.com/swagger-api/swagger-core/issues/3046

TransactionsResource now has support for optional query params "limit" and "offset"
    so that only a subset of large results can be requested.

UtilsResource added to provide convenient Base64<->Base58 conversions.

/admin/uptime fixed to return uptime from application launch instead of
    instantiation of AdminResource class!

Controller improved to detect repository and API startup failures.

HSQLDBRepositoryFactory now detects when it can't open database and throws.
(Before it would simply hang).

Removed extraneous import from qora.account.Account
2018-12-07 17:42:31 +00:00
catbref
28c2cdaf5b FATJAR packaging + block explorer changes
Switched from maven-assembly-plugin to maven-shade-plugin for
building FATJAR.
When running from FATJAR, class-path is ". .." to help find
log4j2.properties file.

Swagger-UI can now be served direct from inside FATJAR instead
of requiring resources in filesystem.

Default package Start now controller/Controller

block-explorer.html now served via Jetty and modified to use
relative URLs instead of absolute http://localhost:9085/... style

Improved shutdown code in controller

/admin/stop API call disabled for now

Highly permissive settings.json added
2018-12-05 11:32:55 +00:00
catbref
ad9fa9bf9d More work on API plus basic block explorer
Added FATJAR packaging support to pom.xml

Added some "summary" fields to API calls but more need doing.
Corrected path clash from having unnecessary @OpenAPIDefinition annotations.
Added API "tags" to group similar calls (address-based, block-related, etc.)
Fixed addresses/lastreference/{address}
Implemented addresses/lastreference/{address}/unconfirmed
Implemented addresses/assets/{address}
Added /admin/stop and /admin/uptime API calls.
Moved general API info into new src/api/ApiDefinition.java
Added CORS support to ApiService
Added /transactions/address/{address} and /transactions/block/{signature}

Replaced references to test.Common.* to do with repository factory.
 This fixes issues with building FATJAR due to references to test classes
 that are omitted from FATJAR.

Changes to AccountBalanceData, BlockData and TransactionData
 to support JAX-RS rendering to JSON.

Added getUnconfirmedLastReference() to Account.

Added getAllBalances(address) to account repository
 - returns all asset balances for that address.

Added getAllSignaturesInvolvingAddress(address) to account repository
 but currently only uses TransactionRecipients HSQLDB table.
 (And even that wasn't automatically populated).

Included: very basic block explorer to be opened in browser as a file:
block-explorer.html
2018-12-04 16:34:55 +00:00
catbref
90094be95a CIYAM-ATv2 can be used with any asset, not just QORA.
Some initial BTC cross-chain support. (Needs more work).

Unified timestamp for V2 switchover to block version 4,
applicable to several transaction types.

Qora-specific interface to CIYAM ATv2 library.

Beware: some areas still work-in-progress!
2018-12-03 13:05:38 +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
01ee7dd7e3 CHANGED: some more method implementations in AddressesResource 2018-10-22 14:59:35 +02:00
Kc
193f8d05c4 CHANGED: implemented AddressResource.getLastReference(..) 2018-10-21 16:32:06 +02:00
Kc
11c8af4b0c ADDED: AddressResource + method stubs 2018-10-21 15:17:37 +02:00
Kc
ac33b927e6 CHANGED: implemented generating balance and time methods in BlocksResource 2018-10-20 20:58:29 +02:00
Kc
6590863201 CHANGED: simplified API error annotations in API resources
FIXED: ApiErrorFactory used no context path and wrong translation key
CHANGED: renamed parameters in Translator for consistency
2018-10-20 01:29:20 +02:00
Kc
d2aab4b446 CHANGED: removed obsolete API methods from BlocksResource
CHANGED: added missing response schemas
2018-10-19 12:35:15 +02:00
Kc
a075705885 ADDED: Swagger UI for API documentation 2018-10-18 20:29:07 +02:00
catbref
46eee3cbce More work on CIYAM AT support.
ATs can create AT-Transactions which contain payments (of any asset) and/or messages.

Legacy Qora1 DeployATTransactions create AT records in the repository but set to "finished"
so that they never execute.

More repository support for ATs.

In HSQLDB, create a new TYPE called ATStateHash which is used to verify the same AT outcome
on a per-block basis.
Added Accounts.account as a foreign key to AccountBalances with ON DELETE CASCADE.
ATStates now include state_hash and fees on a per-block basis.
ATTransactions now include asset_id.

When transforming DeployATTransactions, don't include any signature when collating bytes for signing!
2018-10-15 15:12:41 +01:00
Kc
23b8fcc96e CHANGED: implemented more BlocksResource methods
CHANGED: added dependency to javax.mail for because of strange "java.lang.NoClassDefFoundError: javax/mail/internet/MimeMultipart" exception when serializing data objects in API resources.
2018-10-15 15:11:22 +02:00
Kc
aff81c2806 CHANGED: removed double output 2018-10-14 22:00:27 +02:00
Kc
74a49baaf3 CHANGED: removed obsolete comment 2018-10-14 20:49:32 +02:00
Kc
9a3eb186cc CHANGED: translation support for API resources 2018-10-14 20:35:49 +02:00
Kc
2eb808a0b7 CHANGED: added comment
CHANGED: default locale
2018-10-12 08:27:49 +02:00
Kc
2d0ced5a72 CHANGED: finished AnnotationPostProcessor for translating swagger annotations
CHANGED: fixed Translator bug that would ignore all translation templates
2018-10-12 08:21:44 +02:00
Kc
b57881bc50 ADDED: post processor stub for API resource annotations 2018-10-11 08:56:25 +02: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
aa7bdaf713 CHANGED: read translations from XML files 2018-10-04 16:36:45 +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
Kc
75adc7453c Better help messages
FIXED: save ApiClient.translator
CHANGED: ApiClient now respects more resource annotations for building help messages (success and error responses)
CHANGED: Added more detailed annotations to BlocksResource
2018-09-28 20:41:41 +02:00
Kc
646462942c ADDED: globalization.Translator - basic globalization support (implementation needed)
ADDED: api.Security (implementation needed)
ADDED: api.APIErrorFactory
CHANGED: added command execution to ApiClient
2018-09-24 00:21:47 +02:00
Kc
19a9a3a98b CHANGED: integrated Swagger/OpenApi
CHANGED: added method stubs and describing annotations to BlocksResource
2018-09-20 23:48:20 +02:00
Kc
4f279fc616 ADDED: ApiClient
ADDED: UsageDescription annotation
ADDED: Start class as entry point

first implementation of annotated resource descriptions
2018-09-18 23:41:37 +02:00
Kc
d63ff02b97 CHANGED: added first API resources with jetty and jersey 2018-09-16 23:24:20 +02:00
Kc
9fb434cdd6 CHANGED: fixed ApiService 2018-09-02 10:35:13 +02:00
Kc
2fc74ac583 Added reference to Jersey for RESTful services.
Added Api package.
Added BlocksResource as first candidate for API implementation.
2018-08-30 07:01:28 +02:00
catbref
ad250e57c8 Fix issues with payments, asset trades and voting.
Some payments don't always initialize the recipient's
last reference, depending on whether the asset is QORA or not and
what type of transaction is being processed.
Calls to Payment.process/orphan now take boolean to indicate
whether recipient's last reference should always be initialized
regardless of asset.
("initialized" here means setting an initial last reference for
an account if the current value is null/empty/missing)

When matching orders to produce trades, it isn't enough to only
sort orders with best price first. Orders with the same price also
need to be further sorted by earliest order first. (This was
implicitly done in Qora v1). Added additional ORDER BY sub-clause
to achieve this and improved the corresponding table index too.

Converted a lot of logging from simplistic System.out/err.println
to Apache log4j2. Added several "trace"-level logging statements
to aid debugging which can be activated given appropriate
configuration in log4j2.properties.

With voting, detection of previous votes was broken during orphan
as previousOptionIndex was set to 0 instead of null when fetching
a VoteOnPollTransaction from the HSQLDB repository. This was due
to lack of null-checking - now fixed.
Corresponding changes made in IssueAsset and Message
transaction HSQLDB repository classes.

v1feeder now syncs up to block 99055. Block 99056 contains DeployAT.
Orphaning back to block 1 and then resync works without issue too.
2018-08-08 17:02:41 +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
9651192a2d Rollout conditional signature serialization to remaining transaction types.
Also added/corrected some JavaDoc.
2018-06-28 08:36:12 +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
795da06505 Refactor stupid getResultSetBytes() method & fix migrate
* Replaced occurances of "this.repository.getResultSetBytes(resultSet.getBinaryStream(index))"
with "resultSet.getBytes(index)"

* Replaced corresponding preparedStatement.setBinaryStream() with preparedStatement.setBytes()

* Fixed migrate app so DB can be rebuilt using old v1 Qora client
2018-06-19 16:49:42 +01:00
catbref
5e674cbaab Added Create Poll Transaction support (untested)
* Moved Asset issue/deissue code from IssueAssetTransaction to Asset business object.
* Added more constructors for Asset using IssueAssetTransactionData or assetId.

* Moved some constants from transaction transfers to business objects (e.g. IssueAssetTransaction)
(They might now make more sense being in Asset)

* Changed some transaction isValid() checks to use transaction's timestamp instead of NTP.getTime()

* New VotingRepository - as yet unimplemented

Really need to rewrite "migrate" and add a ton of unit tests.
2018-06-19 12:30:17 +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
9897981de1 Work on assets/payments
* Created PaymentData transfer objects for (recipient, assetId, amount) tuples
* Created corresponding Payment class for validating, processing and orphaning payment(s)

* Modified OrderData to support isClosed for when an Order is cancelled so no more trades can occur

* Migrated CancelOrderTransactions and MultiPaymentTransactions

* Converted MessageTransactions, PaymentTransactions and TransferAssetTransactions to use new Payment class

Can't use PaymentTransformer in PaymentTransformer or TransferAssetTransformer due to serialization differences.
2018-06-14 16:46:55 +01:00
catbref
2f8c160627 More migration of Assets/Orders and TransferAssetTransactions 2018-06-14 13:09:55 +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
c5818543ea Correct wrong constructors in HSQLDB*TransactionRepository classes 2018-06-13 17:11:55 +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
f2d7a3d0cd Converted Message Transactions 2018-06-13 15:40:58 +01:00
catbref
16a92305d2 Conversion of Payment Transactions
+ some fixes spotted en route
2018-06-13 15:01:26 +01:00
catbref
a0824b21d4 Converted most of CreateOrderTransaction
Some tidying up of other transaction-related repositories and transformers.
2018-06-13 14:29:15 +01:00
catbref
519331f823 Work on Assets conversion
* Added AssetData transfer object
* Added IssueAssetTransactionData transfer object

* Reworked qora.assets.Asset into business layer object
* Reworked qora.transaction.IssueAssetTransaction into business layer object

* Added corresponding AssetRepository and support in TransactionRepository et al

* Fixed BlockChain in line with asset changes

* Some renaming inside GenesisTransaction to reflect use of transfer object, not business object

* Business transaction objects now take Repository param

* Moved HSQLDB transaction repositories into a sub-package
* Changed HSQLDBSaver.execute(Connection connection) to .execute(Repository repository) to fix visibility issues
and allow repository more control in the future if need be

* Changed from "return null" statements in HSQLDB repositories to throw DataException when an error occurs.
Better to throw than to silently return null?

* Added static version of PublicKeyAccount.verify() for when a repository-backed PublicKeyAccount is not needed

* Fixed getter/setter code template incorrectly producing "this.this.field = param"
2018-06-13 11:46:33 +01:00
catbref
698c4b6cc9 More repository work
Moved more repository-like methods from qora.* classes to repository.

Removed qora.block.BlockTransaction as it's pretty much internal to the HSQLDB repository.

Fixing qora.account.*

Fixing genesis-related classes: block, account, transaction...
2018-06-12 14:54:06 +01:00
catbref
37d9bcbb53 Repository work
Rolled BlockTransactionRepository into BlockRepository.

Added AccountRepository for general account info and account balances.

BlockTransformer now takes Block as param instead of BlockData as it needs Block's transactions.
2018-06-12 12:15:38 +01:00
catbref
d45c33fe90 More work on repository
No need for database.DB class as the code is specific to HSQLDB so moved into relevant repository.hsqldb classes.

Top-level Repository instance (e.g. HSQLDBRepository) is used within subclasses, e.g. HSQLDBBlockRepository, so they
can share the same repository state, like underlying SQL Connection for easier transactional support.

HSQLDBRepository subclasses now call checkedExecute() on top-level repository instance, instead of passing Connection
to obsolete DB.checkedExecute.

No need for qora.block.BlockFactory any more as those methods are now in repository.

More work on Blocks and Transactions in general.
2018-06-12 10:21:03 +01:00
catbref
6853f0edcb
Merge branch 'DAO' into DAO 2018-06-12 08:34:03 +01:00
catbref
8220113613 WORK IN PROGRESS
Still converting to repository layout.
This commit is just in case my dev computer blows up and also for interim code review.

Removed data.block.BlockData as an interface (with data.block.Block as implementation) for now.
2018-06-11 12:09:16 +01:00
Kc
efb43c67fb CHANGED: added support for DB transactions (commit/rollback) to repository 2018-06-11 00:26:26 +02:00
Kc
0f16b1588c more refactoring 2018-06-09 00:29:21 +02:00
Kc
749baf8843 *** NOT FINAL, NOT TESTED ***
added data access class for block
added HSQLDB repository with reader methods for block data
started usage of repository and data objects in BlockFactory
2018-06-08 21:31:31 +02: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
3b02432b73 more work on DAO - for illustrative purposes only!! 2018-06-08 13:30:12 +01:00
catbref
a0345412e8 first stab at repository interfaces and hsqldb implementations 2018-06-07 09:15:54 +01:00
catbref
2ea6f12b3c First stub files for conversion to data access layer, etc. 2018-06-06 21:16:50 +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
216ed7c772 Better code for saving to database, using close-coupled column-value pairs 2018-05-25 15:23:10 +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