Repository: QuincySx/BlockchainWallet-Crypto
Branch: master
Commit: 8025525c2746
Files: 122
Total size: 650.3 KB
Directory structure:
gitextract_ei6psuhp/
├── .gitignore
├── LICENSE
├── README.md
├── build.gradle
├── gradle/
│ └── wrapper/
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
├── library/
│ ├── .gitignore
│ ├── build.gradle
│ ├── proguard-rules.pro
│ └── src/
│ ├── androidTest/
│ │ └── java/
│ │ └── com/
│ │ └── quincysx/
│ │ └── crypto/
│ │ └── ExampleInstrumentedTest.java
│ ├── main/
│ │ ├── AndroidManifest.xml
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── quincysx/
│ │ │ └── crypto/
│ │ │ ├── CoinTypes.java
│ │ │ ├── ECKeyPair.java
│ │ │ ├── ECPublicKey.java
│ │ │ ├── Key.java
│ │ │ ├── SecureCharSequence.java
│ │ │ ├── Transaction.java
│ │ │ ├── TrulySecureRandom.java
│ │ │ ├── bip32/
│ │ │ │ ├── ExtendedKey.java
│ │ │ │ ├── Index.java
│ │ │ │ └── ValidationException.java
│ │ │ ├── bip38/
│ │ │ │ ├── Bip38.java
│ │ │ │ └── Rijndael.java
│ │ │ ├── bip39/
│ │ │ │ ├── ByteUtils.java
│ │ │ │ ├── CharSequenceComparators.java
│ │ │ │ ├── CharSequenceSplitter.java
│ │ │ │ ├── MnemonicGenerator.java
│ │ │ │ ├── MnemonicValidator.java
│ │ │ │ ├── NFKDNormalizer.java
│ │ │ │ ├── Normalization.java
│ │ │ │ ├── PBKDF2WithHmacSHA512.java
│ │ │ │ ├── RandomSeed.java
│ │ │ │ ├── SeedCalculator.java
│ │ │ │ ├── SeedCalculatorByWordListLookUp.java
│ │ │ │ ├── SpongyCastlePBKDF2WithHmacSHA512.java
│ │ │ │ ├── WordCount.java
│ │ │ │ ├── WordList.java
│ │ │ │ ├── WordListMapNormalization.java
│ │ │ │ ├── exception/
│ │ │ │ │ └── MnemonicException.java
│ │ │ │ ├── validation/
│ │ │ │ │ ├── InvalidChecksumException.java
│ │ │ │ │ ├── InvalidWordCountException.java
│ │ │ │ │ ├── UnexpectedWhiteSpaceException.java
│ │ │ │ │ └── WordNotFoundException.java
│ │ │ │ └── wordlists/
│ │ │ │ ├── English.java
│ │ │ │ ├── French.java
│ │ │ │ ├── Japanese.java
│ │ │ │ └── Spanish.java
│ │ │ ├── bip44/
│ │ │ │ ├── Account.java
│ │ │ │ ├── AddressIndex.java
│ │ │ │ ├── BIP44.java
│ │ │ │ ├── Change.java
│ │ │ │ ├── CoinPairDerive.java
│ │ │ │ ├── CoinType.java
│ │ │ │ ├── M.java
│ │ │ │ └── Purpose.java
│ │ │ ├── bitcoin/
│ │ │ │ ├── BTCTransaction.java
│ │ │ │ ├── BitCoinECKeyPair.java
│ │ │ │ ├── BitcoinException.java
│ │ │ │ ├── BitcoinInputStream.java
│ │ │ │ └── BitcoinOutputStream.java
│ │ │ ├── eip55/
│ │ │ │ └── EthCheckAddress.java
│ │ │ ├── eos/
│ │ │ │ └── EOSECKeyPair.java
│ │ │ ├── ethereum/
│ │ │ │ ├── Bloom.java
│ │ │ │ ├── ByteArrayWrapper.java
│ │ │ │ ├── CallTransaction.java
│ │ │ │ ├── ECDSASignature.java
│ │ │ │ ├── EthECKeyPair.java
│ │ │ │ ├── EthTransaction.java
│ │ │ │ ├── config/
│ │ │ │ │ └── Constants.java
│ │ │ │ ├── keystore/
│ │ │ │ │ ├── CipherException.java
│ │ │ │ │ ├── KeyStore.java
│ │ │ │ │ └── KeyStoreFile.java
│ │ │ │ ├── rlp/
│ │ │ │ │ ├── CompactEncoder.java
│ │ │ │ │ ├── DecodeResult.java
│ │ │ │ │ ├── RLP.java
│ │ │ │ │ ├── RLPElement.java
│ │ │ │ │ ├── RLPItem.java
│ │ │ │ │ ├── RLPList.java
│ │ │ │ │ └── Value.java
│ │ │ │ ├── solidity/
│ │ │ │ │ └── SolidityType.java
│ │ │ │ ├── utils/
│ │ │ │ │ ├── ByteUtil.java
│ │ │ │ │ └── FastByteComparisons.java
│ │ │ │ └── vm/
│ │ │ │ ├── DataWord.java
│ │ │ │ └── LogInfo.java
│ │ │ ├── exception/
│ │ │ │ ├── CoinNotFindException.java
│ │ │ │ └── NonSupportException.java
│ │ │ └── utils/
│ │ │ ├── BTCUtils.java
│ │ │ ├── Base58.java
│ │ │ ├── Base58Check.java
│ │ │ ├── Base64.java
│ │ │ ├── HexUtils.java
│ │ │ ├── HmacSha512.java
│ │ │ ├── KECCAK256.java
│ │ │ ├── RIPEMD160.java
│ │ │ └── SHA256.java
│ │ └── res/
│ │ └── values/
│ │ └── strings.xml
│ └── test/
│ └── java/
│ └── com/
│ └── quincysx/
│ └── crypto/
│ ├── Bip32UnitTest.java
│ ├── Bip39UnitTest.java
│ ├── Bip44UnitTest.java
│ ├── Eip55UnitTest.java
│ ├── ExampleUnitTest.java
│ └── HashUnitTest.java
├── sample/
│ ├── .gitignore
│ ├── build.gradle
│ ├── proguard-rules.pro
│ └── src/
│ ├── androidTest/
│ │ └── java/
│ │ └── com/
│ │ └── quincysx/
│ │ └── crypto/
│ │ └── ExampleInstrumentedTest.java
│ ├── main/
│ │ ├── AndroidManifest.xml
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── quincysx/
│ │ │ └── crypto/
│ │ │ └── smpale/
│ │ │ ├── Main1Activity.java
│ │ │ └── MainActivity.java
│ │ └── res/
│ │ ├── drawable/
│ │ │ └── ic_launcher_background.xml
│ │ ├── drawable-v24/
│ │ │ └── ic_launcher_foreground.xml
│ │ ├── layout/
│ │ │ └── activity_main.xml
│ │ ├── mipmap-anydpi-v26/
│ │ │ ├── ic_launcher.xml
│ │ │ └── ic_launcher_round.xml
│ │ └── values/
│ │ ├── colors.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test/
│ └── java/
│ └── com/
│ └── quincysx/
│ └── crypto/
│ └── ExampleUnitTest.java
└── settings.gradle
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
*.iml
.gradle
/local.properties
/.idea/workspace.xml
/.idea/libraries
.idea/
.DS_Store
/build
/captures
.externalNativeBuild
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
================================================
FILE: README.md
================================================
# BlockchainWallet-Crypto
[](https://jitpack.io/#QuincySx/BlockchainWallet-Crypto)
# 长时间不维护可移步 https://github.com/QuincySx/ChainWallet
#### 简介
##### 这个库到底能干什么
1. 生成比特币公私钥地址
2. 生成以太坊公私钥地址
3. 根据 UTXO 信息打包比特币交易
4. 根据 nonce 信息打包以太坊交易
5. 对比特币交易进行签名
6. 对以太坊交易进行签名
7. 支持 BIP39 助记词
8. 支持 BIP32 子私钥
9. 支持 BIP44 多币种管理
10. 支持 BIP38 加密私钥导入导出
11. 支持以太坊 keystore 导入导出
12. 生成以太坊调用智能合约的参数
13. 生成 EOS 公私钥
#### EOS 从助记词生成私钥
现在 EOS 从助记词生成私钥有两种方式
1. 12 个助记词之间用空格隔开拼接成字符串,然后 Hash 得到私钥
2. 采用 Bip44 标准的生成方案,EOS 的币种序号详见最下方⎡相关资料⎦中的⎡Bip44 注册币种列表⎦
经过国内大部分钱包商议统一使用第二种方案解决 EOS 从助记词生成私钥的问题
#### 欢迎给位提设计上的 lssues 和 pr
#### 引入项目
```
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
dependencies {
implementation 'com.github.QuincySx:BlockchainWallet-Crypto:last-version'
}
```
#### 使用说明
[简单使用说明](https://github.com/QuincySx/BlockchainWallet-Crypto/wiki)
## 相关资料
[Bip44 注册币种列表](https://github.com/satoshilabs/slips/blob/master/slip-0044.md)
## LICENSE
[开源协议](LICENSE)
================================================
FILE: build.gradle
================================================
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
#Tue Mar 27 20:02:31 CST 2018
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip
================================================
FILE: gradle.properties
================================================
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
================================================
FILE: gradlew
================================================
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
================================================
FILE: gradlew.bat
================================================
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
================================================
FILE: library/.gitignore
================================================
/build
================================================
FILE: library/build.gradle
================================================
apply plugin: 'com.android.library'
android {
compileSdkVersion 27
defaultConfig {
minSdkVersion 15
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
api fileTree(dir: 'libs', include: ['*.jar'])
api "com.cedarsoftware:java-util:1.8.0"
api "com.fasterxml.jackson.core:jackson-databind:2.8.5"
api 'com.madgag.spongycastle:core:1.58.0.0'
api 'com.madgag.spongycastle:prov:1.58.0.0'
api 'com.lambdaworks:scrypt:1.4.0'
}
================================================
FILE: library/proguard-rules.pro
================================================
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
================================================
FILE: library/src/androidTest/java/com/quincysx/crypto/ExampleInstrumentedTest.java
================================================
package com.quincysx.crypto;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see Testing documentation
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.quincysx.crypto.test", appContext.getPackageName());
}
}
================================================
FILE: library/src/main/AndroidManifest.xml
================================================
================================================
FILE: library/src/main/java/com/quincysx/crypto/CoinTypes.java
================================================
package com.quincysx.crypto;
import com.quincysx.crypto.exception.CoinNotFindException;
/**
* Created by q7728 on 2018/3/18.
*/
public enum CoinTypes {
Bitcoin(0, "BTC"),
BitcoinTest(1, "BTC"),
Litecoin(2, "LTC"),
Dogecoin(3, "DOGE"),
Ethereum(60, "ETH"),
EOS(194, "EOS");
private int coinType;
private String coinName;
CoinTypes(int i, String name) {
coinType = i;
coinName = name;
}
public int coinType() {
return coinType;
}
public String coinName() {
return coinName;
}
public static CoinTypes parseCoinType(int type) throws CoinNotFindException {
for (CoinTypes e : CoinTypes.values()) {
if (e.coinType == type) {
return e;
}
}
throw new CoinNotFindException("The currency is not supported for the time being");
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/ECKeyPair.java
================================================
/*
* Copyright 2013 bits of proof zrt.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.quincysx.crypto;
import com.quincysx.crypto.bip32.ValidationException;
import com.quincysx.crypto.utils.RIPEMD160;
import org.spongycastle.asn1.ASN1InputStream;
import org.spongycastle.asn1.DERInteger;
import org.spongycastle.asn1.DLSequence;
import org.spongycastle.asn1.sec.SECNamedCurves;
import org.spongycastle.asn1.x9.X9ECParameters;
import org.spongycastle.crypto.AsymmetricCipherKeyPair;
import org.spongycastle.crypto.generators.ECKeyPairGenerator;
import org.spongycastle.crypto.params.ECDomainParameters;
import org.spongycastle.crypto.params.ECKeyGenerationParameters;
import org.spongycastle.crypto.params.ECPrivateKeyParameters;
import org.spongycastle.crypto.params.ECPublicKeyParameters;
import org.spongycastle.crypto.signers.ECDSASigner;
import org.spongycastle.math.ec.ECPoint;
import org.spongycastle.util.Arrays;
import java.io.IOException;
import java.math.BigInteger;
import java.security.SecureRandom;
public class ECKeyPair implements Key {
protected static final SecureRandom secureRandom = new SecureRandom();
protected static final X9ECParameters CURVE = SECNamedCurves.getByName("secp256k1");
protected static final ECDomainParameters domain = new ECDomainParameters(CURVE.getCurve(),
CURVE.getG(), CURVE.getN(), CURVE.getH());
protected static final BigInteger LARGEST_PRIVATE_KEY = new BigInteger
("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", 16);
protected BigInteger priv;
protected byte[] pub;
protected byte[] pubComp;
protected boolean compressed;
protected ECKeyPair() {
}
public ECKeyPair(byte[] p, boolean compressed) throws ValidationException {
this(new BigInteger(1, p), compressed);
if (!(p.length == 32 || p.length == 43 )) {
throw new ValidationException("Invalid private key");
}
}
public ECKeyPair(BigInteger priv, boolean compressed) {
this.priv = priv;
this.compressed = compressed;
ECPoint multiply = CURVE.getG().multiply(priv);
this.pub = multiply.getEncoded(false);
this.pubComp = multiply.getEncoded(true);
}
protected ECKeyPair(Key keyPair) {
this.priv = new BigInteger(1, keyPair.getRawPrivateKey());
this.compressed = keyPair.isCompressed();
this.pub = Arrays.clone(keyPair.getRawPublicKey(false));
this.pubComp = Arrays.clone(keyPair.getRawPublicKey());
}
@Override
public boolean isCompressed() {
return compressed;
}
@Override
public ECKeyPair clone() throws CloneNotSupportedException {
ECKeyPair c = (ECKeyPair) super.clone();
c.priv = new BigInteger(c.priv.toByteArray());
c.pub = Arrays.clone(pub);
c.pubComp = Arrays.clone(pubComp);
c.compressed = compressed;
return c;
}
public static ECKeyPair createNew(boolean compressed) {
ECKeyPairGenerator generator = new ECKeyPairGenerator();
ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(domain,
secureRandom);
generator.init(keygenParams);
AsymmetricCipherKeyPair keypair = generator.generateKeyPair();
ECPrivateKeyParameters privParams = (ECPrivateKeyParameters) keypair.getPrivate();
ECPublicKeyParameters pubParams = (ECPublicKeyParameters) keypair.getPublic();
ECKeyPair k = new ECKeyPair();
k.priv = privParams.getD();
k.compressed = compressed;
ECPoint multiply = CURVE.getG().multiply(k.priv);
k.pub = multiply.getEncoded(false);
k.pubComp = multiply.getEncoded(true);
return k;
}
public void setPublic(byte[] pub) throws ValidationException {
throw new ValidationException("Can not set public key if private is present");
}
@Override
public byte[] getRawPrivateKey() {
byte[] p = priv.toByteArray();
if (p.length != 32) {
byte[] tmp = new byte[32];
System.arraycopy(p, Math.max(0, p.length - 32), tmp, Math.max(0, 32 - p.length), Math
.min(32, p.length));
p = tmp;
}
return p;
}
@Override
public byte[] getRawPublicKey(boolean isCompressed) {
if (isCompressed) {
return Arrays.clone(pubComp);
} else {
return Arrays.clone(pub);
}
}
@Override
public byte[] getRawPublicKey() {
return getRawPublicKey(true);
}
@Override
public byte[] getRawAddress() {
return RIPEMD160.hash160(pubComp);
}
@Override
public String getPrivateKey() {
throw new RuntimeException("No formatted private Key");
}
@Override
public String getPublicKey() {
throw new RuntimeException("No formatted public Key");
}
@Override
public String getAddress() {
throw new RuntimeException("No formatted address");
}
@Override
public T sign(byte[] messageHash) throws ValidationException {
throw new ValidationException("Please convert to ECKeyPair subclass signature");
}
public static boolean verify(byte[] hash, byte[] signature, byte[] pub) {
ASN1InputStream asn1 = new ASN1InputStream(signature);
try {
ECDSASigner signer = new ECDSASigner();
signer.init(false, new ECPublicKeyParameters(CURVE.getCurve().decodePoint(pub),
domain));
DLSequence seq = (DLSequence) asn1.readObject();
BigInteger r = ((DERInteger) seq.getObjectAt(0)).getPositiveValue();
BigInteger s = ((DERInteger) seq.getObjectAt(1)).getPositiveValue();
return signer.verifySignature(hash, r, s);
} catch (Exception e) {
// threat format errors as invalid signatures
return false;
} finally {
try {
asn1.close();
} catch (IOException e) {
}
}
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/ECPublicKey.java
================================================
/*
* Copyright 2013 bits of proof zrt.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.quincysx.crypto;
import com.quincysx.crypto.utils.RIPEMD160;
import org.spongycastle.util.Arrays;
public class ECPublicKey implements Key {
private byte[] pub;
private boolean compressed;
public ECPublicKey(byte[] pub, boolean compressed) {
this.pub = pub;
this.compressed = compressed;
}
@Override
public boolean isCompressed() {
return compressed;
}
public void setCompressed(boolean compressed) {
this.compressed = compressed;
}
@Override
public byte[] getRawPrivateKey() {
throw new RuntimeException("Please use private key to sign signature");
}
@Override
public byte[] getRawPublicKey(boolean isCompressed) {
if (!isCompressed) {
throw new RuntimeException("No compressed public key");
}
return Arrays.clone(pub);
}
@Override
public byte[] getRawPublicKey() {
return Arrays.clone(pub);
}
@Override
public byte[] getRawAddress() {
return RIPEMD160.hash160(pub);
}
@Override
public String getPrivateKey() {
throw new RuntimeException("Please use private key to sign signature");
}
@Override
public String getPublicKey() {
throw new RuntimeException("No formatted public Key");
}
@Override
public String getAddress() {
throw new RuntimeException("No formatted address");
}
@Override
public ECPublicKey clone() throws CloneNotSupportedException {
ECPublicKey c = (ECPublicKey) super.clone();
c.pub = Arrays.clone(pub);
return c;
}
@Override
public T sign(byte[] messageHash) {
throw new RuntimeException("Please use private key to sign signature");
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/Key.java
================================================
/*
* Copyright 2013 bits of proof zrt.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.quincysx.crypto;
import com.quincysx.crypto.bip32.ValidationException;
public interface Key extends Cloneable {
/**
* 获取原生私钥
*
* @return
*/
public byte[] getRawPrivateKey();
/**
* 获取公钥
*
* @param isCompressed 是否压缩
* @return 原生公钥
*/
public byte[] getRawPublicKey(boolean isCompressed);
/**
* 获取原生压缩公钥
*
* @return
*/
public byte[] getRawPublicKey();
/**
* 获取地址
*
* @return
*/
public byte[] getRawAddress();
/**
* 获取格式化的私钥
*
* @return
*/
public String getPrivateKey();
/**
* 获取格式化的公钥
*
* @return
*/
public String getPublicKey();
/**
* 获取格式化的地址
*
* @return
*/
public String getAddress();
/**
* 获取判断公钥是否是压缩格式
*
* @return
*/
public boolean isCompressed();
public Key clone() throws CloneNotSupportedException;
public T sign(byte[] messageHash) throws ValidationException;
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/SecureCharSequence.java
================================================
package com.quincysx.crypto;
import java.security.SecureRandom;
import java.util.Arrays;
/**
* @author QuincySx
* @date 2018/3/9 下午2:57
*/
public class SecureCharSequence implements CharSequence {
private char[] chars;
public SecureCharSequence(CharSequence charSequence) {
this(charSequence, 0, charSequence.length());
}
public SecureCharSequence(char[] chars) {
wipe();
this.chars = chars;
}
private SecureCharSequence(CharSequence charSequence, int start, int end) {
// pulled from http://stackoverflow.com/a/15844273
wipe();
int length = end - start;
chars = new char[length];
for (int i = start;
i < end;
i++) {
chars[i - start] = charSequence.charAt(i);
}
}
public void wipe() {
if (chars != null) {
Arrays.fill(chars, ' ');
SecureRandom r = new SecureRandom();
byte[] bytes = new byte[chars.length];
r.nextBytes(bytes);
for (int i = 0;
i < chars.length;
i++) {
chars[i] = (char) bytes[i];
}
Arrays.fill(chars, ' ');
}
}
protected void finalize() {
wipe();
}
@Override
public int length() {
if (chars != null) {
return chars.length;
}
return 0;
}
@Override
public char charAt(int index) {
if (chars != null) {
return chars[index];
}
return 0;
}
@Override
public String toString() {
return String.valueOf(this.chars);
}
@Override
public boolean equals(Object o) {
if (o instanceof SecureCharSequence) {
return Arrays.equals(chars, ((SecureCharSequence) o).chars);
}
return false;
}
@Override
public CharSequence subSequence(int start, int end) {
SecureCharSequence s = new SecureCharSequence(this, start, end);
return s;
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/Transaction.java
================================================
package com.quincysx.crypto;
import com.quincysx.crypto.bip32.ValidationException;
/**
* @author QuincySx
* @date 2018/3/8 下午1:56
*/
public interface Transaction {
byte[] sign(ECKeyPair key) throws ValidationException;
public byte[] getSignBytes();
/**
* Eth 使用的方法
*
* @return
*/
public byte[] getData();
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/TrulySecureRandom.java
================================================
/*
The MIT License (MIT)
Copyright (c) 2013 Valentin Konovalov
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/
package com.quincysx.crypto;
import android.os.Build;
import android.os.SystemClock;
import android.util.Log;
import com.quincysx.crypto.utils.HexUtils;
import org.spongycastle.crypto.digests.SHA256Digest;
import org.spongycastle.crypto.prng.DigestRandomGenerator;
import org.spongycastle.crypto.prng.ThreadedSeedGenerator;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class TrulySecureRandom extends java.security.SecureRandom {
private static final String TAG = "SecureRandom";
private final DigestRandomGenerator generator;
private boolean initialized;
public TrulySecureRandom() {
generator = new DigestRandomGenerator(new SHA256Digest());
}
public void addSeedMaterial(long seed) {
generator.addSeedMaterial(seed);
}
private void addSeedMaterial(byte[] seed) {
generator.addSeedMaterial(seed);
}
@Override
public int nextInt() {
byte[] buf = new byte[4];
nextBytes(buf);
return ((buf[0] & 0xff) << 24) | ((buf[1] & 0xff) << 16) | ((buf[2] & 0xff) << 8) | (buf[3] & 0xff);
}
@Override
public int nextInt(int n) {
return Math.abs(nextInt()) % n;
}
@Override
public synchronized void nextBytes(byte[] bytes) {
if (!initialized) {
long start = System.currentTimeMillis();
ThreadedSeedGenerator threadedSeedGenerator = new ThreadedSeedGenerator();
do {
addSeedMaterial(threadedSeedGenerator.generateSeed(64, true));
try {
Thread.sleep(1);
} catch (InterruptedException ignored) {
}
addSeedMaterial(threadedSeedGenerator.generateSeed(32, false));
} while (Math.abs(System.currentTimeMillis() - start) < 1000);
addSeedMaterial(System.nanoTime());
addSeedMaterial(System.currentTimeMillis());
addSeedMaterial(SystemClock.elapsedRealtime());
addSeedMaterial(SystemClock.currentThreadTimeMillis());
addSeedMaterial(new java.security.SecureRandom().generateSeed(128));
addSeedMaterial(("" + Build.DEVICE + Build.MODEL + Build.TIME + Build.VERSION.SDK_INT).getBytes());
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
Future future = executor.submit(new Runnable() {
@Override
public void run() {
byte[] devRandomSeed = getDevRandomSeed();
if (devRandomSeed != null) {
addSeedMaterial(devRandomSeed);
}
}
});
future.get(3, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Log.v(TAG, "/dev/random read interrupted");
} catch (ExecutionException e) {
Log.e(TAG, "/dev/random read error");
} catch (TimeoutException e) {
Log.w(TAG, "/dev/random read timeout");
} finally {
executor.shutdownNow();
}
initialized = true;
}
generator.nextBytes(bytes);
}
@Override
public String getAlgorithm() {
return "BouncyCastle";
}
private byte[] getDevRandomSeed() {
byte[] buf = null;
File file = new File("/dev/random");
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
buf = new byte[16];
for (int i = 0; i < buf.length; i++) {
int ch = inputStream.read();
if (ch == -1) {
return null;
}
buf[i] = (byte) ch;
}
} catch (Exception ignored) {
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException ignored) {
}
}
}
return buf;
}
@Override
public void setSeed(byte[] seed) {
Log.w("SecureRandom", "setting seed " + HexUtils.toHex(seed) + " was ignored");
}
@Override
public void setSeed(long seed) {
Log.w("SecureRandom", "setting seed " + seed + " was ignored");
}
@Override
public byte[] generateSeed(int numBytes) {
throw new RuntimeException("not supported");
}
@Override
public boolean nextBoolean() {
throw new RuntimeException("not supported");
}
@Override
public double nextDouble() {
throw new RuntimeException("not supported");
}
@Override
public float nextFloat() {
throw new RuntimeException("not supported");
}
@Override
public synchronized double nextGaussian() {
throw new RuntimeException("not supported");
}
@Override
public long nextLong() {
throw new RuntimeException("not supported");
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/bip32/ExtendedKey.java
================================================
/*
* Copyright 2013 bits of proof zrt.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.quincysx.crypto.bip32;
import com.quincysx.crypto.ECKeyPair;
import com.quincysx.crypto.ECPublicKey;
import com.quincysx.crypto.Key;
import com.quincysx.crypto.utils.Base58Check;
import org.spongycastle.asn1.sec.SECNamedCurves;
import org.spongycastle.asn1.x9.X9ECParameters;
import org.spongycastle.crypto.generators.SCrypt;
import org.spongycastle.math.ec.ECPoint;
import org.spongycastle.util.Arrays;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* Key Generator following BIP32 https://en.bitcoin.it/wiki/BIP_0032
*/
public class ExtendedKey {
private static final SecureRandom rnd = new SecureRandom();
private static final X9ECParameters curve = SECNamedCurves.getByName("secp256k1");
private final Key master;
private final byte[] chainCode;
private final int depth;
private final int parent;
private final int sequence;
private static final byte[] BITCOIN_SEED = "Bitcoin seed".getBytes();
public static ExtendedKey createFromPassphrase(String passphrase, byte[] encrypted) throws
ValidationException {
try {
byte[] key = SCrypt.generate(passphrase.getBytes("UTF-8"), BITCOIN_SEED, 16384, 8, 8,
32);
SecretKeySpec keyspec = new SecretKeySpec(key, "AES");
if (encrypted.length == 32) {
// asssume encrypted is seed
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding", "BC");
cipher.init(Cipher.DECRYPT_MODE, keyspec);
return create(cipher.doFinal(encrypted));
} else {
// assume encrypted serialization of a key
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
byte[] iv = Arrays.copyOfRange(encrypted, 0, 16);
byte[] data = Arrays.copyOfRange(encrypted, 16, encrypted.length);
cipher.init(Cipher.DECRYPT_MODE, keyspec, new IvParameterSpec(iv));
return ExtendedKey.parse(new String(cipher.doFinal(data)));
}
} catch (UnsupportedEncodingException e) {
throw new ValidationException(e);
} catch (IllegalBlockSizeException e) {
throw new ValidationException(e);
} catch (BadPaddingException e) {
throw new ValidationException(e);
} catch (InvalidKeyException e) {
throw new ValidationException(e);
} catch (NoSuchAlgorithmException e) {
throw new ValidationException(e);
} catch (NoSuchProviderException e) {
throw new ValidationException(e);
} catch (NoSuchPaddingException e) {
throw new ValidationException(e);
} catch (InvalidAlgorithmParameterException e) {
throw new ValidationException(e);
}
}
public byte[] encrypt(String passphrase, boolean production) throws ValidationException {
try {
byte[] key = SCrypt.generate(passphrase.getBytes("UTF-8"), BITCOIN_SEED, 16384, 8, 8,
32);
SecretKeySpec keyspec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, keyspec);
byte[] iv = cipher.getIV();
byte[] c = cipher.doFinal(serialize(production).getBytes());
byte[] result = new byte[iv.length + c.length];
System.arraycopy(iv, 0, result, 0, iv.length);
System.arraycopy(c, 0, result, iv.length, c.length);
return result;
} catch (UnsupportedEncodingException | NoSuchAlgorithmException |
NoSuchProviderException | NoSuchPaddingException | InvalidKeyException
| IllegalBlockSizeException | BadPaddingException e) {
throw new ValidationException(e);
}
}
public static ExtendedKey create(byte[] seed) throws ValidationException {
try {
Mac mac = Mac.getInstance("HmacSHA512", "BC");
SecretKey seedkey = new SecretKeySpec(BITCOIN_SEED, "HmacSHA512");
mac.init(seedkey);
byte[] lr = mac.doFinal(seed);
byte[] l = Arrays.copyOfRange(lr, 0, 32);
byte[] r = Arrays.copyOfRange(lr, 32, 64);
BigInteger m = new BigInteger(1, l);
if (m.compareTo(curve.getN()) >= 0) {
throw new ValidationException("This is rather unlikely, but it did just happen");
}
ECKeyPair keyPair = new ECKeyPair(l, true);
return new ExtendedKey(keyPair, r, 0, 0, 0);
} catch (NoSuchAlgorithmException e) {
throw new ValidationException(e);
} catch (NoSuchProviderException e) {
throw new ValidationException(e);
} catch (InvalidKeyException e) {
throw new ValidationException(e);
}
}
public static ExtendedKey createNew() {
Key key = ECKeyPair.createNew(true);
byte[] chainCode = new byte[32];
rnd.nextBytes(chainCode);
return new ExtendedKey(key, chainCode, 0, 0, 0);
}
/**
* @param bytes
* @return
* @throws ValidationException
* @deprecated
*/
public static ExtendedKey parsePrivateKey(byte[] bytes) throws ValidationException {
Key key = new ECKeyPair(bytes, true);
byte[] chainCode = new byte[32];
rnd.nextBytes(chainCode);
return new ExtendedKey(key, chainCode, 0, 0, 0);
}
public ExtendedKey(Key key, byte[] chainCode, int depth, int parent, int sequence) {
this.master = key;
this.chainCode = chainCode;
this.parent = parent;
this.depth = depth;
this.sequence = sequence;
}
public Key getMaster() {
return master;
}
public byte[] getChainCode() {
return Arrays.clone(chainCode);
}
public int getDepth() {
return depth;
}
public int getParent() {
return parent;
}
public int getSequence() {
return sequence;
}
public int getFingerPrint() {
int fingerprint = 0;
byte[] address = master.getRawAddress();
for (int i = 0; i < 4; ++i) {
fingerprint <<= 8;
fingerprint |= address[i] & 0xff;
}
return fingerprint;
}
public Key getKey(int sequence) throws ValidationException {
return generateKey(sequence).getMaster();
}
public ExtendedKey getChild(int sequence) throws ValidationException {
ExtendedKey sub = generateKey(sequence);
return new ExtendedKey(sub.getMaster(), sub.getChainCode(), sub.getDepth() + 1,
getFingerPrint(), sequence);
}
public ExtendedKey getReadOnly() {
return new ExtendedKey(new ECPublicKey(master.getRawPublicKey(), true), chainCode, depth,
parent, sequence);
}
public boolean isReadOnly() {
return master.getRawPrivateKey() == null;
}
private ExtendedKey generateKey(int sequence) throws ValidationException {
try {
if ((sequence & 0x80000000) != 0 && master.getRawPrivateKey() == null) {
throw new ValidationException("need private key for private generation");
}
Mac mac = Mac.getInstance("HmacSHA512", "BC");
SecretKey key = new SecretKeySpec(chainCode, "HmacSHA512");
mac.init(key);
byte[] extended;
byte[] pub = master.getRawPublicKey();
if ((sequence & 0x80000000) == 0) {
extended = new byte[pub.length + 4];
System.arraycopy(pub, 0, extended, 0, pub.length);
extended[pub.length] = (byte) ((sequence >>> 24) & 0xff);
extended[pub.length + 1] = (byte) ((sequence >>> 16) & 0xff);
extended[pub.length + 2] = (byte) ((sequence >>> 8) & 0xff);
extended[pub.length + 3] = (byte) (sequence & 0xff);
} else {
byte[] priv = master.getRawPrivateKey();
extended = new byte[priv.length + 5];
System.arraycopy(priv, 0, extended, 1, priv.length);
extended[priv.length + 1] = (byte) ((sequence >>> 24) & 0xff);
extended[priv.length + 2] = (byte) ((sequence >>> 16) & 0xff);
extended[priv.length + 3] = (byte) ((sequence >>> 8) & 0xff);
extended[priv.length + 4] = (byte) (sequence & 0xff);
}
byte[] lr = mac.doFinal(extended);
byte[] l = Arrays.copyOfRange(lr, 0, 32);
byte[] r = Arrays.copyOfRange(lr, 32, 64);
BigInteger m = new BigInteger(1, l);
if (m.compareTo(curve.getN()) >= 0) {
throw new ValidationException("This is rather unlikely, but it did just happen");
}
if (master.getRawPrivateKey() != null) {
BigInteger k = m.add(new BigInteger(1, master.getRawPrivateKey())).mod(curve.getN
());
if (k.equals(BigInteger.ZERO)) {
throw new ValidationException("This is rather unlikely, but it did just " +
"happen");
}
return new ExtendedKey(new ECKeyPair(k, true), r, depth, parent, sequence);
} else {
ECPoint q = curve.getG().multiply(m).add(curve.getCurve().decodePoint(pub));
if (q.isInfinity()) {
throw new ValidationException("This is rather unlikely, but it did just " +
"happen");
}
pub = new ECPoint.Fp(curve.getCurve(), q.getX(), q.getY(), true).getEncoded();
return new ExtendedKey(new ECPublicKey(pub, true), r, depth, parent, sequence);
}
} catch (NoSuchAlgorithmException e) {
throw new ValidationException(e);
} catch (NoSuchProviderException e) {
throw new ValidationException(e);
} catch (InvalidKeyException e) {
throw new ValidationException(e);
}
}
private static final byte[] xprv = new byte[]{0x04, (byte) 0x88, (byte) 0xAD, (byte) 0xE4};
private static final byte[] xpub = new byte[]{0x04, (byte) 0x88, (byte) 0xB2, (byte) 0x1E};
private static final byte[] tprv = new byte[]{0x04, (byte) 0x35, (byte) 0x83, (byte) 0x94};
private static final byte[] tpub = new byte[]{0x04, (byte) 0x35, (byte) 0x87, (byte) 0xCF};
public String serialize(boolean production) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
if (master.getRawPrivateKey() != null) {
if (production) {
out.write(xprv);
} else {
out.write(tprv);
}
} else {
if (production) {
out.write(xpub);
} else {
out.write(tpub);
}
}
out.write(depth & 0xff);
out.write((parent >>> 24) & 0xff);
out.write((parent >>> 16) & 0xff);
out.write((parent >>> 8) & 0xff);
out.write(parent & 0xff);
out.write((sequence >>> 24) & 0xff);
out.write((sequence >>> 16) & 0xff);
out.write((sequence >>> 8) & 0xff);
out.write(sequence & 0xff);
out.write(chainCode);
if (master.getRawPrivateKey() != null) {
out.write(0x00);
out.write(master.getRawPrivateKey());
} else {
out.write(master.getRawPublicKey());
}
} catch (IOException e) {
}
return Base58Check.bytesToBase58(out.toByteArray());
}
public static ExtendedKey parse(String serialized) throws ValidationException {
byte[] data = Base58Check.base58ToBytes(serialized);
if (data.length != 78) {
throw new ValidationException("invalid extended key");
}
byte[] type = Arrays.copyOf(data, 4);
boolean hasPrivate;
if (Arrays.areEqual(type, xprv) || Arrays.areEqual(type, tprv)) {
hasPrivate = true;
} else if (Arrays.areEqual(type, xpub) || Arrays.areEqual(type, tpub)) {
hasPrivate = false;
} else {
throw new ValidationException("invalid magic number for an extended key");
}
int depth = data[4] & 0xff;
int parent = data[5] & 0xff;
parent <<= 8;
parent |= data[6] & 0xff;
parent <<= 8;
parent |= data[7] & 0xff;
parent <<= 8;
parent |= data[8] & 0xff;
int sequence = data[9] & 0xff;
sequence <<= 8;
sequence |= data[10] & 0xff;
sequence <<= 8;
sequence |= data[11] & 0xff;
sequence <<= 8;
sequence |= data[12] & 0xff;
byte[] chainCode = Arrays.copyOfRange(data, 13, 13 + 32);
byte[] pubOrPriv = Arrays.copyOfRange(data, 13 + 32, data.length);
Key key;
if (hasPrivate) {
key = new ECKeyPair(new BigInteger(1, pubOrPriv), true);
} else {
key = new ECPublicKey(pubOrPriv, true);
}
return new ExtendedKey(key, chainCode, depth, parent, sequence);
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/bip32/Index.java
================================================
package com.quincysx.crypto.bip32;
/**
* @author QuincySx
* @date 2018/3/5 下午4:29
*/
public final class Index {
Index() {
}
public static int hard(final int index) {
return index | 0x80000000;
}
public static boolean isHardened(final int i) {
return (i & 0x80000000) != 0;
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/bip32/ValidationException.java
================================================
/*
* Copyright 2013 bits of proof zrt.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.quincysx.crypto.bip32;
public class ValidationException extends Exception
{
private static final long serialVersionUID = 1L;
public ValidationException(Throwable cause)
{
super (cause);
}
public ValidationException(String message, Throwable cause)
{
super (message, cause);
}
public ValidationException(String message)
{
super (message);
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/bip38/Bip38.java
================================================
package com.quincysx.crypto.bip38;
import com.quincysx.crypto.bip32.ValidationException;
import com.quincysx.crypto.bitcoin.BitCoinECKeyPair;
import com.quincysx.crypto.utils.Base58;
import com.quincysx.crypto.utils.HexUtils;
import com.quincysx.crypto.utils.SHA256;
import org.spongycastle.crypto.generators.SCrypt;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;
/**
* @author QuincySx
* @date 2018/3/8 下午2:41
*/
public class Bip38 {
//官方推荐参数 性能差的手机耗时特别长
private static final int SCRYPT_N = 16384;
private static final int SCRYPT_R = 8;
private static final int SCRYPT_P = 8;
//性能差的手机也秒出,安全性差
// private static final int SCRYPT_N = 1024;
// private static final int SCRYPT_R = 1;
// private static final int SCRYPT_P = 1;
private static final int SCRYPT_LENGTH = 64;
private static final BigInteger n = new BigInteger(1, HexUtils.fromHex("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"));
/**
* Encrypt a SIPA formatted private key with a passphrase using BIP38.
*
* This is a helper function that does everything in one go. You can call the
* individual functions if you wish to separate it into more phases.
*
* @throws InterruptedException
*/
public static String encryptNoEcMultiply(CharSequence passphrase, String base58EncodedPrivateKey) throws ValidationException, InterruptedException {
byte[] tmp = Base58.decode(base58EncodedPrivateKey);
int version = tmp[0] & 0xFF;
byte[] bytes = new byte[tmp.length - 4 - 1];
System.arraycopy(tmp, 1, bytes, 0, bytes.length);
boolean compressed = true;
if (bytes.length == 33 && bytes[32] == 1) {
compressed = true;
bytes = java.util.Arrays.copyOf(bytes, 32); // Chop off the additional marker byte.
} else if (bytes.length == 32) {
compressed = false;
}
boolean testNet = false;
if (version == BitCoinECKeyPair.TEST_NET_PRIVATE_KEY_PREFIX) {
testNet = true;
} else if (version == BitCoinECKeyPair.MAIN_NET_PRIVATE_KEY_PREFIX) {
testNet = false;
}
Arrays.fill(tmp, (byte) 0);
BitCoinECKeyPair bitCoinECKeyPair = new BitCoinECKeyPair(bytes, testNet, compressed);
byte[] salt = Bip38.calculateScryptSalt(bitCoinECKeyPair.getAddress());
byte[] stretchedKeyMaterial = bip38Stretch1(passphrase, salt, SCRYPT_LENGTH);
return encryptNoEcMultiply(stretchedKeyMaterial, bitCoinECKeyPair, salt);
}
/**
* Perform BIP38 compatible password stretching on a password to derive the
* BIP38 key material
*
* @throws InterruptedException
*/
public static byte[] bip38Stretch1(CharSequence passphrase, byte[] salt, int outputSize)
throws InterruptedException {
byte[] passwordBytes = null;
byte[] derived;
try {
passwordBytes = convertToByteArray(passphrase);
derived = SCrypt.generate(passwordBytes, salt, SCRYPT_N, SCRYPT_R, SCRYPT_P, outputSize
);
return derived;
} finally {
// Zero the password bytes.
if (passwordBytes != null) {
java.util.Arrays.fill(passwordBytes, (byte) 0);
}
}
}
private static byte[] convertToByteArray(CharSequence charSequence) {
if (charSequence == null) {
throw new RuntimeException("charSequence not NULL");
}
ByteBuffer bb = Charset.forName("UTF-8").encode(CharBuffer.wrap(charSequence));
byte[] result = new byte[bb.remaining()];
bb.get(result);
bb.clear();
byte[] clearTest = new byte[bb.remaining()];
java.util.Arrays.fill(clearTest, (byte) 0);
bb.put(clearTest);
return result;
}
public static String encryptNoEcMultiply(byte[] stretcedKeyMaterial, BitCoinECKeyPair key, byte[] salt) {
int checksumLength = 4;
byte[] encoded = new byte[39 + checksumLength];
int index = 0;
encoded[index++] = (byte) 0x01;
encoded[index++] = (byte) 0x42;
byte non_EC_multiplied = (byte) 0xC0;
byte compressedPublicKey = key.isCompressed() ? (byte) 0x20 : (byte) 0;
encoded[index++] = (byte) (non_EC_multiplied | compressedPublicKey);
// Salt
System.arraycopy(salt, 0, encoded, index, salt.length);
index += salt.length;
// Derive Keys
byte[] derivedHalf1 = new byte[32];
System.arraycopy(stretcedKeyMaterial, 0, derivedHalf1, 0, 32);
byte[] derivedHalf2 = new byte[32];
System.arraycopy(stretcedKeyMaterial, 32, derivedHalf2, 0, 32);
// Initialize AES key
Rijndael aes = new Rijndael();
aes.makeKey(derivedHalf2, 256);
// Get private key bytes
byte[] complete = key.getRawPrivateKey();
// Insert first encrypted key part
byte[] toEncryptPart1 = new byte[16];
for (int i = 0; i < 16; i++) {
toEncryptPart1[i] = (byte) ((((int) complete[i]) & 0xFF) ^ (((int) derivedHalf1[i]) & 0xFF));
}
byte[] encryptedHalf1 = new byte[16];
aes.encrypt(toEncryptPart1, encryptedHalf1);
System.arraycopy(encryptedHalf1, 0, encoded, index, encryptedHalf1.length);
index += encryptedHalf1.length;
// Insert second encrypted key part
byte[] toEncryptPart2 = new byte[16];
for (int i = 0; i < 16; i++) {
toEncryptPart2[i] = (byte) ((((int) complete[16 + i]) & 0xFF) ^ (((int) derivedHalf1[16 + i]) & 0xFF));
}
byte[] encryptedHalf2 = new byte[16];
aes.encrypt(toEncryptPart2, encryptedHalf2);
System.arraycopy(encryptedHalf2, 0, encoded, index, encryptedHalf2.length);
index += encryptedHalf2.length;
// Checksum
byte[] checkSum = SHA256.doubleSha256(encoded, 0, 39);
byte[] start = new byte[4];
System.arraycopy(checkSum, 0, start, 0, 4);
System.arraycopy(start, 0, encoded, 39, checksumLength);
// Base58 encode
return Base58.encode(encoded);
}
public static boolean isBip38PrivateKey(String bip38PrivateKey) {
return parseBip38PrivateKey(bip38PrivateKey) != null;
}
public static class Bip38PrivateKey {
public boolean ecMultiply;
public boolean compressed;
public boolean lotSequence;
public byte[] salt;
public byte[] data;
public Bip38PrivateKey(boolean ecMultiply, boolean compressed, boolean lotSequence, byte[] salt, byte[] data) {
this.ecMultiply = ecMultiply;
this.compressed = compressed;
this.lotSequence = lotSequence;
this.salt = salt;
this.data = data;
}
}
public static Bip38PrivateKey parseBip38PrivateKey(String bip38PrivateKey) {
// Decode Base 58
byte[] decoded = Base58.decode(bip38PrivateKey);
if (decoded == null) {
return null;
}
//Validate length
if (!(decoded.length == 39 || decoded.length == 43)) {
return null;
}
int index = 0;
// Validate BIP 38 prefix
if (decoded[index++] != (byte) 0x01) {
return null;
}
boolean ecMultiply;
if (decoded[index] == (byte) 0x42) {
ecMultiply = false;
} else if (decoded[index] == (byte) 0x43) {
ecMultiply = true;
} else {
return null;
}
index++;
// Validate flags and determine whether we have a compressed key
int flags = ((int) decoded[index++]) & 0x00ff;
boolean lotSequence;
if (ecMultiply) {
if ((flags | 0x0024) != 0x24) {
// Only bit 3 and 6 can be set for EC-multiply keys
return null;
}
lotSequence = (flags & 0x0004) == 0 ? false : true;
} else {
if ((flags | 0x00E0) != 0xE0) {
// Only bit 6 7 and 8 can be set for non-EC-multiply keys
return null;
}
if ((flags & 0x00c0) != 0x00c0) {
// Upper two bits must be set for non-EC-multiplied key
return null;
}
lotSequence = false;
}
boolean compressed = (flags & 0x0020) == 0 ? false : true;
// Fetch salt
byte[] salt = new byte[4];
salt[0] = decoded[index++];
salt[1] = decoded[index++];
salt[2] = decoded[index++];
salt[3] = decoded[index++];
// Fetch data
byte[] data = new byte[32];
System.arraycopy(decoded, index, data, 0, data.length);
index += data.length;
return new Bip38PrivateKey(ecMultiply, compressed, lotSequence, salt, data);
}
/**
* 可能为 Null ,Null 代表密码不正确
*/
public static BitCoinECKeyPair decrypt(String bip38PrivateKeyString, CharSequence passphrase) throws InterruptedException, ValidationException {
Bip38PrivateKey bip38Key = parseBip38PrivateKey(bip38PrivateKeyString);
if (bip38Key == null) {
return null;
}
if (bip38Key.ecMultiply) {
return decryptEcMultiply(bip38Key, passphrase);
} else {
byte[] stretcedKeyMaterial = bip38Stretch1(passphrase, bip38Key.salt, SCRYPT_LENGTH);
return decryptNoEcMultiply(bip38Key, stretcedKeyMaterial);
}
}
public static BitCoinECKeyPair decryptEcMultiply(Bip38PrivateKey bip38Key, CharSequence passphrase
) throws InterruptedException, ValidationException {
// Get 8 byte Owner Salt
byte[] ownerEntropy = new byte[8];
System.arraycopy(bip38Key.data, 0, ownerEntropy, 0, 8);
byte[] ownerSalt = ownerEntropy;
if (bip38Key.lotSequence) {
ownerSalt = new byte[4];
System.arraycopy(ownerEntropy, 0, ownerSalt, 0, 4);
}
// Stretch to get Pass Factor
byte[] passFactor = bip38Stretch1(passphrase, ownerSalt, 32);
if (bip38Key.lotSequence) {
byte[] tmp = new byte[40];
System.arraycopy(passFactor, 0, tmp, 0, 32);
System.arraycopy(ownerEntropy, 0, tmp, 32, 8);
//we convert to byte[] here since this can be a sha256 or Scrypt result.
// might make sense to introduce a 32 byte scrypt type
passFactor = SHA256.doubleSha256(tmp);
}
// Determine Pass Point
BitCoinECKeyPair bitCoinECKeyPair = new BitCoinECKeyPair(passFactor, false, bip38Key.compressed);
byte[] passPoint = bitCoinECKeyPair.getRawPublicKey();
// Get 8 byte encrypted part 1, only first half of encrypted part 1
// (the rest is encrypted within encryptedpart2)
byte[] encryptedPart1 = new byte[16];
System.arraycopy(bip38Key.data, 8, encryptedPart1, 0, 8);
// Get 16 byte encrypted part 2
byte[] encryptedPart2 = new byte[16];
System.arraycopy(bip38Key.data, 16, encryptedPart2, 0, 16);
// Second stretch to derive decryption key
byte[] saltPlusOwnerSalt = new byte[12];
System.arraycopy(bip38Key.salt, 0, saltPlusOwnerSalt, 0, 4);
System.arraycopy(ownerEntropy, 0, saltPlusOwnerSalt, 4, 8);
// byte[] derived = SCrypt.generate(passPoint, saltPlusOwnerSalt, 1024, 1, 1, 64);
byte[] derived = SCrypt.generate(passPoint, saltPlusOwnerSalt, SCRYPT_N, SCRYPT_R, SCRYPT_P, SCRYPT_LENGTH);
byte[] derivedQuater1 = new byte[16];
System.arraycopy(derived, 0, derivedQuater1, 0, 16);
byte[] derivedQuater2 = new byte[16];
System.arraycopy(derived, 16, derivedQuater2, 0, 16);
byte[] derivedHalf2 = new byte[32];
System.arraycopy(derived, 32, derivedHalf2, 0, 32);
Rijndael aes = new Rijndael();
aes.makeKey(derivedHalf2, 256);
byte[] unencryptedPart2 = new byte[16];
aes.decrypt(encryptedPart2, unencryptedPart2);
xorBytes(derivedQuater2, unencryptedPart2);
// Get second half of encrypted half 1
System.arraycopy(unencryptedPart2, 0, encryptedPart1, 8, 8);
// Decrypt part 1
byte[] unencryptedPart1 = new byte[16];
aes.decrypt(encryptedPart1, unencryptedPart1);
xorBytes(derivedQuater1, unencryptedPart1);
// Recover seedB
byte[] seedB = new byte[24];
System.arraycopy(unencryptedPart1, 0, seedB, 0, 16);
System.arraycopy(unencryptedPart2, 8, seedB, 16, 8);
// Generate factorB
byte[] factorB = SHA256.doubleSha256(seedB);
BigInteger privateKey = new BigInteger(1, passFactor).multiply(new BigInteger(1, factorB).mod(n));
byte[] keyBytes = new byte[32];
byte[] bytes = privateKey.toByteArray();
if (bytes.length <= keyBytes.length) {
System.arraycopy(bytes, 0, keyBytes, keyBytes.length - bytes.length, bytes.length);
} else {
assert bytes.length == 33 && bytes[0] == 0;
System.arraycopy(bytes, 1, keyBytes, 0, bytes.length - 1);
}
BitCoinECKeyPair ecKeyPair = verify(keyBytes, bip38Key.salt, false, bip38Key.compressed);
if (ecKeyPair == null) {
return verify(keyBytes, bip38Key.salt, true, bip38Key.compressed);
}
return ecKeyPair;
}
public static BitCoinECKeyPair decryptNoEcMultiply(Bip38PrivateKey bip38Key, byte[] stretcedKeyMaterial) throws ValidationException {
// Derive Keys
byte[] derivedHalf1 = new byte[32];
System.arraycopy(stretcedKeyMaterial, 0, derivedHalf1, 0, 32);
byte[] derivedHalf2 = new byte[32];
System.arraycopy(stretcedKeyMaterial, 32, derivedHalf2, 0, 32);
// Initialize AES key
Rijndael aes = new Rijndael();
aes.makeKey(derivedHalf2, 256);
// Fetch first encrypted half
byte[] encryptedHalf1 = new byte[16];
System.arraycopy(bip38Key.data, 0, encryptedHalf1, 0, encryptedHalf1.length);
// Fetch second encrypted half
byte[] encryptedHalf2 = new byte[16];
System.arraycopy(bip38Key.data, 16, encryptedHalf2, 0, encryptedHalf2.length);
byte[] decryptedHalf1 = new byte[16];
aes.decrypt(encryptedHalf1, decryptedHalf1);
byte[] decryptedHalf2 = new byte[16];
aes.decrypt(encryptedHalf2, decryptedHalf2);
byte[] complete = new byte[32];
for (int i = 0; i < 16; i++) {
complete[i] = (byte) ((((int) decryptedHalf1[i]) & 0xFF) ^ (((int) derivedHalf1[i]) & 0xFF));
complete[i + 16] = (byte) ((((int) decryptedHalf2[i]) & 0xFF) ^ (((int) derivedHalf1[i + 16]) & 0xFF));
}
BitCoinECKeyPair bitCoinECKeyPair = verify(complete, bip38Key.salt, false, bip38Key.compressed);
if (bitCoinECKeyPair == null) {
return verify(complete, bip38Key.salt, true, bip38Key.compressed);
}
return bitCoinECKeyPair;
}
private static BitCoinECKeyPair verify(byte[] complete, byte[] salt, boolean testNet, boolean compress) throws ValidationException {
BitCoinECKeyPair bitCoinECKeyPair = new BitCoinECKeyPair(complete, testNet, compress);
byte[] newSalt = calculateScryptSalt(bitCoinECKeyPair.getAddress());
if (!java.util.Arrays.equals(salt, newSalt)) {
// The passphrase is either invalid or we are on the wrong network
return null;
}
return bitCoinECKeyPair;
}
public static byte[] calculateScryptSalt(String address) {
byte[] hash = SHA256.doubleSha256(address.getBytes());
byte[] ret = new byte[4];
System.arraycopy(hash, 0, ret, 0, 4);
return ret;
}
private static void xorBytes(byte[] toApply, byte[] target) {
if (toApply.length != target.length) {
throw new RuntimeException();
}
for (int i = 0; i < toApply.length; i++) {
target[i] = (byte) (target[i] ^ toApply[i]);
}
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/bip38/Rijndael.java
================================================
package com.quincysx.crypto.bip38;
/**
* @author QuincySx
* @date 2018/3/9 下午2:09
*/
public final class Rijndael {
public Rijndael() {
}
/**
* Flag to setup the encryption key schedule.
*/
public static final int DIR_ENCRYPT = 1;
/**
* Flag to setup the decryption key schedule.
*/
public static final int DIR_DECRYPT = 2;
/**
* Flag to setup both key schedules (encryption/decryption).
*/
public static final int DIR_BOTH = (DIR_ENCRYPT | DIR_DECRYPT);
/**
* AES block size in bits
* (N.B. the Rijndael algorithm itself allows for other sizes).
*/
public static final int BLOCK_BITS = 128;
/**
* AES block size in bytes
* (N.B. the Rijndael algorithm itself allows for other sizes).
*/
public static final int BLOCK_SIZE = (BLOCK_BITS >>> 3);
/**
* Substitution table (S-box).
*/
private static final String SS =
"\u637C\u777B\uF26B\u6FC5\u3001\u672B\uFED7\uAB76" +
"\uCA82\uC97D\uFA59\u47F0\uADD4\uA2AF\u9CA4\u72C0" +
"\uB7FD\u9326\u363F\uF7CC\u34A5\uE5F1\u71D8\u3115" +
"\u04C7\u23C3\u1896\u059A\u0712\u80E2\uEB27\uB275" +
"\u0983\u2C1A\u1B6E\u5AA0\u523B\uD6B3\u29E3\u2F84" +
"\u53D1\u00ED\u20FC\uB15B\u6ACB\uBE39\u4A4C\u58CF" +
"\uD0EF\uAAFB\u434D\u3385\u45F9\u027F\u503C\u9FA8" +
"\u51A3\u408F\u929D\u38F5\uBCB6\uDA21\u10FF\uF3D2" +
"\uCD0C\u13EC\u5F97\u4417\uC4A7\u7E3D\u645D\u1973" +
"\u6081\u4FDC\u222A\u9088\u46EE\uB814\uDE5E\u0BDB" +
"\uE032\u3A0A\u4906\u245C\uC2D3\uAC62\u9195\uE479" +
"\uE7C8\u376D\u8DD5\u4EA9\u6C56\uF4EA\u657A\uAE08" +
"\uBA78\u252E\u1CA6\uB4C6\uE8DD\u741F\u4BBD\u8B8A" +
"\u703E\uB566\u4803\uF60E\u6135\u57B9\u86C1\u1D9E" +
"\uE1F8\u9811\u69D9\u8E94\u9B1E\u87E9\uCE55\u28DF" +
"\u8CA1\u890D\uBFE6\u4268\u4199\u2D0F\uB054\uBB16";
private static final byte[]
Se = new byte[256];
private static final int[]
Te0 = new int[256],
Te1 = new int[256],
Te2 = new int[256],
Te3 = new int[256];
private static final byte[]
Sd = new byte[256];
private static final int[]
Td0 = new int[256],
Td1 = new int[256],
Td2 = new int[256],
Td3 = new int[256];
/**
* Round constants
*/
private static final int[]
rcon = new int[10]; /* for 128-bit blocks, Rijndael never uses more than 10 rcon values */
/**
* Number of rounds (depends on key size).
*/
private int Nr = 0;
private int Nk = 0;
private int Nw = 0;
/**
* Encryption key schedule
*/
private int rek[] = null;
/**
* Decryption key schedule
*/
private int rdk[] = null;
static {
/*
Te0[x] = Se[x].[02, 01, 01, 03];
Te1[x] = Se[x].[03, 02, 01, 01];
Te2[x] = Se[x].[01, 03, 02, 01];
Te3[x] = Se[x].[01, 01, 03, 02];
Td0[x] = Sd[x].[0e, 09, 0d, 0b];
Td1[x] = Sd[x].[0b, 0e, 09, 0d];
Td2[x] = Sd[x].[0d, 0b, 0e, 09];
Td3[x] = Sd[x].[09, 0d, 0b, 0e];
*/
int ROOT = 0x11B;
int s1, s2, s3, i1, i2, i4, i8, i9, ib, id, ie, t;
for (i1 = 0; i1 < 256; i1++) {
char c = SS.charAt(i1 >>> 1);
s1 = (byte) ((i1 & 1) == 0 ? c >>> 8 : c) & 0xff;
s2 = s1 << 1;
if (s2 >= 0x100) {
s2 ^= ROOT;
}
s3 = s2 ^ s1;
i2 = i1 << 1;
if (i2 >= 0x100) {
i2 ^= ROOT;
}
i4 = i2 << 1;
if (i4 >= 0x100) {
i4 ^= ROOT;
}
i8 = i4 << 1;
if (i8 >= 0x100) {
i8 ^= ROOT;
}
i9 = i8 ^ i1;
ib = i9 ^ i2;
id = i9 ^ i4;
ie = i8 ^ i4 ^ i2;
Se[i1] = (byte) s1;
Te0[i1] = t = (s2 << 24) | (s1 << 16) | (s1 << 8) | s3;
Te1[i1] = (t >>> 8) | (t << 24);
Te2[i1] = (t >>> 16) | (t << 16);
Te3[i1] = (t >>> 24) | (t << 8);
Sd[s1] = (byte) i1;
Td0[s1] = t = (ie << 24) | (i9 << 16) | (id << 8) | ib;
Td1[s1] = (t >>> 8) | (t << 24);
Td2[s1] = (t >>> 16) | (t << 16);
Td3[s1] = (t >>> 24) | (t << 8);
}
/*
* round constants
*/
int r = 1;
rcon[0] = r << 24;
for (int i = 1; i < 10; i++) {
r <<= 1;
if (r >= 0x100) {
r ^= ROOT;
}
rcon[i] = r << 24;
}
}
/**
* Expand a cipher key into a full encryption key schedule.
*
* @param cipherKey the cipher key (128, 192, or 256 bits).
*/
private void expandKey(byte[] cipherKey) {
int temp, r = 0;
for (int i = 0, k = 0; i < Nk; i++, k += 4) {
rek[i] =
((cipherKey[k]) << 24) |
((cipherKey[k + 1] & 0xff) << 16) |
((cipherKey[k + 2] & 0xff) << 8) |
((cipherKey[k + 3] & 0xff));
}
for (int i = Nk, n = 0; i < Nw; i++, n--) {
temp = rek[i - 1];
if (n == 0) {
n = Nk;
temp =
((Se[(temp >>> 16) & 0xff]) << 24) |
((Se[(temp >>> 8) & 0xff] & 0xff) << 16) |
((Se[(temp) & 0xff] & 0xff) << 8) |
((Se[(temp >>> 24)] & 0xff));
temp ^= rcon[r++];
} else if (Nk == 8 && n == 4) {
temp =
((Se[(temp >>> 24)]) << 24) |
((Se[(temp >>> 16) & 0xff] & 0xff) << 16) |
((Se[(temp >>> 8) & 0xff] & 0xff) << 8) |
((Se[(temp) & 0xff] & 0xff));
}
rek[i] = rek[i - Nk] ^ temp;
}
temp = 0;
}
/*
* Faster implementation of the key expansion
* (only worthwhile in Rijndael is used in a hashing function mode).
*/
/*
private void expandKey(byte[] cipherKey) {
int keyOffset = 0;
int i = 0;
int temp;
rek[0] =
(cipherKey[ 0] ) << 24 |
(cipherKey[ 1] & 0xff) << 16 |
(cipherKey[ 2] & 0xff) << 8 |
(cipherKey[ 3] & 0xff);
rek[1] =
(cipherKey[ 4] ) << 24 |
(cipherKey[ 5] & 0xff) << 16 |
(cipherKey[ 6] & 0xff) << 8 |
(cipherKey[ 7] & 0xff);
rek[2] =
(cipherKey[ 8] ) << 24 |
(cipherKey[ 9] & 0xff) << 16 |
(cipherKey[10] & 0xff) << 8 |
(cipherKey[11] & 0xff);
rek[3] =
(cipherKey[12] ) << 24 |
(cipherKey[13] & 0xff) << 16 |
(cipherKey[14] & 0xff) << 8 |
(cipherKey[15] & 0xff);
if (Nk == 4) {
for (;;) {
temp = rek[keyOffset + 3];
rek[keyOffset + 4] = rek[keyOffset] ^
((Se[(temp >>> 16) & 0xff] ) << 24) ^
((Se[(temp >>> 8) & 0xff] & 0xff) << 16) ^
((Se[(temp ) & 0xff] & 0xff) << 8) ^
((Se[(temp >>> 24) ] & 0xff) ) ^
rcon[i];
rek[keyOffset + 5] = rek[keyOffset + 1] ^ rek[keyOffset + 4];
rek[keyOffset + 6] = rek[keyOffset + 2] ^ rek[keyOffset + 5];
rek[keyOffset + 7] = rek[keyOffset + 3] ^ rek[keyOffset + 6];
if (++i == 10) {
return;
}
keyOffset += 4;
}
}
rek[keyOffset + 4] =
(cipherKey[16] ) << 24 |
(cipherKey[17] & 0xff) << 16 |
(cipherKey[18] & 0xff) << 8 |
(cipherKey[19] & 0xff);
rek[keyOffset + 5] =
(cipherKey[20] ) << 24 |
(cipherKey[21] & 0xff) << 16 |
(cipherKey[22] & 0xff) << 8 |
(cipherKey[23] & 0xff);
if (Nk == 6) {
for (;;) {
temp = rek[keyOffset + 5];
rek[keyOffset + 6] = rek[keyOffset] ^
((Se[(temp >>> 16) & 0xff] ) << 24) ^
((Se[(temp >>> 8) & 0xff] & 0xff) << 16) ^
((Se[(temp ) & 0xff] & 0xff) << 8) ^
((Se[(temp >>> 24) ] & 0xff) ) ^
rcon[i];
rek[keyOffset + 7] = rek[keyOffset + 1] ^ rek[keyOffset + 6];
rek[keyOffset + 8] = rek[keyOffset + 2] ^ rek[keyOffset + 7];
rek[keyOffset + 9] = rek[keyOffset + 3] ^ rek[keyOffset + 8];
if (++i == 8) {
return;
}
rek[keyOffset + 10] = rek[keyOffset + 4] ^ rek[keyOffset + 9];
rek[keyOffset + 11] = rek[keyOffset + 5] ^ rek[keyOffset + 10];
keyOffset += 6;
}
}
rek[keyOffset + 6] =
(cipherKey[24] ) << 24 |
(cipherKey[25] & 0xff) << 16 |
(cipherKey[26] & 0xff) << 8 |
(cipherKey[27] & 0xff);
rek[keyOffset + 7] =
(cipherKey[28] ) << 24 |
(cipherKey[29] & 0xff) << 16 |
(cipherKey[30] & 0xff) << 8 |
(cipherKey[31] & 0xff);
if (Nk == 8) {
for (;;) {
temp = rek[keyOffset + 7];
rek[keyOffset + 8] = rek[keyOffset] ^
((Se[(temp >>> 16) & 0xff] ) << 24) ^
((Se[(temp >>> 8) & 0xff] & 0xff) << 16) ^
((Se[(temp ) & 0xff] & 0xff) << 8) ^
((Se[(temp >>> 24) ] & 0xff) ) ^
rcon[i];
rek[keyOffset + 9] = rek[keyOffset + 1] ^ rek[keyOffset + 8];
rek[keyOffset + 10] = rek[keyOffset + 2] ^ rek[keyOffset + 9];
rek[keyOffset + 11] = rek[keyOffset + 3] ^ rek[keyOffset + 10];
if (++i == 7) {
return;
}
temp = rek[keyOffset + 11];
rek[keyOffset + 12] = rek[keyOffset + 4] ^
((Se[(temp >>> 24) ] ) << 24) ^
((Se[(temp >>> 16) & 0xff] & 0xff) << 16) ^
((Se[(temp >>> 8) & 0xff] & 0xff) << 8) ^
((Se[(temp ) & 0xff] & 0xff));
rek[keyOffset + 13] = rek[keyOffset + 5] ^ rek[keyOffset + 12];
rek[keyOffset + 14] = rek[keyOffset + 6] ^ rek[keyOffset + 13];
rek[keyOffset + 15] = rek[keyOffset + 7] ^ rek[keyOffset + 14];
keyOffset += 8;
}
}
}
*/
/**
* Compute the decryption schedule from the encryption schedule .
*/
private void invertKey() {
int d = 0, e = 4 * Nr, w;
/*
* apply the inverse MixColumn transform to all round keys
* but the first and the last:
*/
rdk[d] = rek[e];
rdk[d + 1] = rek[e + 1];
rdk[d + 2] = rek[e + 2];
rdk[d + 3] = rek[e + 3];
d += 4;
e -= 4;
for (int r = 1; r < Nr; r++) {
w = rek[e];
rdk[d] =
Td0[Se[(w >>> 24)] & 0xff] ^
Td1[Se[(w >>> 16) & 0xff] & 0xff] ^
Td2[Se[(w >>> 8) & 0xff] & 0xff] ^
Td3[Se[(w) & 0xff] & 0xff];
w = rek[e + 1];
rdk[d + 1] =
Td0[Se[(w >>> 24)] & 0xff] ^
Td1[Se[(w >>> 16) & 0xff] & 0xff] ^
Td2[Se[(w >>> 8) & 0xff] & 0xff] ^
Td3[Se[(w) & 0xff] & 0xff];
w = rek[e + 2];
rdk[d + 2] =
Td0[Se[(w >>> 24)] & 0xff] ^
Td1[Se[(w >>> 16) & 0xff] & 0xff] ^
Td2[Se[(w >>> 8) & 0xff] & 0xff] ^
Td3[Se[(w) & 0xff] & 0xff];
w = rek[e + 3];
rdk[d + 3] =
Td0[Se[(w >>> 24)] & 0xff] ^
Td1[Se[(w >>> 16) & 0xff] & 0xff] ^
Td2[Se[(w >>> 8) & 0xff] & 0xff] ^
Td3[Se[(w) & 0xff] & 0xff];
d += 4;
e -= 4;
}
rdk[d] = rek[e];
rdk[d + 1] = rek[e + 1];
rdk[d + 2] = rek[e + 2];
rdk[d + 3] = rek[e + 3];
}
/**
* Setup the AES key schedule for encryption, decryption, or both.
*
* @param cipherKey the cipher key (128, 192, or 256 bits).
* @param keyBits size of the cipher key in bits.
* @param direction cipher direction (DIR_ENCRYPT, DIR_DECRYPT, or DIR_BOTH).
*/
public void makeKey(byte[] cipherKey, int keyBits, int direction)
throws RuntimeException {
// check key size:
if (keyBits != 128 && keyBits != 192 && keyBits != 256) {
throw new RuntimeException("Invalid AES key size (" + keyBits + " bits)");
}
Nk = keyBits >>> 5;
Nr = Nk + 6;
Nw = 4 * (Nr + 1);
rek = new int[Nw];
rdk = new int[Nw];
if ((direction & DIR_BOTH) != 0) {
expandKey(cipherKey);
/*
for (int r = 0; r <= Nr; r++) {
System.out.print("RK" + r + "=");
for (int i = 0; i < 4; i++) {
int w = rek[4*r + i];
System.out.print(" " + Integer.toHexString(w));
}
System.out.println();
}
*/
if ((direction & DIR_DECRYPT) != 0) {
invertKey();
}
}
}
/**
* Setup the AES key schedule (any cipher direction).
*
* @param cipherKey the cipher key (128, 192, or 256 bits).
* @param keyBits size of the cipher key in bits.
*/
public void makeKey(byte[] cipherKey, int keyBits)
throws RuntimeException {
makeKey(cipherKey, keyBits, DIR_BOTH);
}
/**
* Encrypt exactly one block (BLOCK_SIZE bytes) of plaintext.
*
* @param pt plaintext block.
* @param ct ciphertext block.
*/
public void encrypt(byte[] pt, byte[] ct) {
/*
* map byte array block to cipher state
* and add initial round key:
*/
int k = 0, v;
int t0 = ((pt[0]) << 24 |
(pt[1] & 0xff) << 16 |
(pt[2] & 0xff) << 8 |
(pt[3] & 0xff)) ^ rek[0];
int t1 = ((pt[4]) << 24 |
(pt[5] & 0xff) << 16 |
(pt[6] & 0xff) << 8 |
(pt[7] & 0xff)) ^ rek[1];
int t2 = ((pt[8]) << 24 |
(pt[9] & 0xff) << 16 |
(pt[10] & 0xff) << 8 |
(pt[11] & 0xff)) ^ rek[2];
int t3 = ((pt[12]) << 24 |
(pt[13] & 0xff) << 16 |
(pt[14] & 0xff) << 8 |
(pt[15] & 0xff)) ^ rek[3];
/*
* Nr - 1 full rounds:
*/
for (int r = 1; r < Nr; r++) {
k += 4;
int a0 =
Te0[(t0 >>> 24)] ^
Te1[(t1 >>> 16) & 0xff] ^
Te2[(t2 >>> 8) & 0xff] ^
Te3[(t3) & 0xff] ^
rek[k];
int a1 =
Te0[(t1 >>> 24)] ^
Te1[(t2 >>> 16) & 0xff] ^
Te2[(t3 >>> 8) & 0xff] ^
Te3[(t0) & 0xff] ^
rek[k + 1];
int a2 =
Te0[(t2 >>> 24)] ^
Te1[(t3 >>> 16) & 0xff] ^
Te2[(t0 >>> 8) & 0xff] ^
Te3[(t1) & 0xff] ^
rek[k + 2];
int a3 =
Te0[(t3 >>> 24)] ^
Te1[(t0 >>> 16) & 0xff] ^
Te2[(t1 >>> 8) & 0xff] ^
Te3[(t2) & 0xff] ^
rek[k + 3];
t0 = a0;
t1 = a1;
t2 = a2;
t3 = a3;
}
/*
* last round lacks MixColumn:
*/
k += 4;
v = rek[k];
ct[0] = (byte) (Se[(t0 >>> 24)] ^ (v >>> 24));
ct[1] = (byte) (Se[(t1 >>> 16) & 0xff] ^ (v >>> 16));
ct[2] = (byte) (Se[(t2 >>> 8) & 0xff] ^ (v >>> 8));
ct[3] = (byte) (Se[(t3) & 0xff] ^ (v));
v = rek[k + 1];
ct[4] = (byte) (Se[(t1 >>> 24)] ^ (v >>> 24));
ct[5] = (byte) (Se[(t2 >>> 16) & 0xff] ^ (v >>> 16));
ct[6] = (byte) (Se[(t3 >>> 8) & 0xff] ^ (v >>> 8));
ct[7] = (byte) (Se[(t0) & 0xff] ^ (v));
v = rek[k + 2];
ct[8] = (byte) (Se[(t2 >>> 24)] ^ (v >>> 24));
ct[9] = (byte) (Se[(t3 >>> 16) & 0xff] ^ (v >>> 16));
ct[10] = (byte) (Se[(t0 >>> 8) & 0xff] ^ (v >>> 8));
ct[11] = (byte) (Se[(t1) & 0xff] ^ (v));
v = rek[k + 3];
ct[12] = (byte) (Se[(t3 >>> 24)] ^ (v >>> 24));
ct[13] = (byte) (Se[(t0 >>> 16) & 0xff] ^ (v >>> 16));
ct[14] = (byte) (Se[(t1 >>> 8) & 0xff] ^ (v >>> 8));
ct[15] = (byte) (Se[(t2) & 0xff] ^ (v));
}
/**
* Decrypt exactly one block (BLOCK_SIZE bytes) of ciphertext.
*
* @param ct ciphertext block.
* @param pt plaintext block.
*/
public void decrypt(byte[] ct, byte[] pt) {
/*
* map byte array block to cipher state
* and add initial round key:
*/
int k = 0, v;
int t0 = ((ct[0]) << 24 |
(ct[1] & 0xff) << 16 |
(ct[2] & 0xff) << 8 |
(ct[3] & 0xff)) ^ rdk[0];
int t1 = ((ct[4]) << 24 |
(ct[5] & 0xff) << 16 |
(ct[6] & 0xff) << 8 |
(ct[7] & 0xff)) ^ rdk[1];
int t2 = ((ct[8]) << 24 |
(ct[9] & 0xff) << 16 |
(ct[10] & 0xff) << 8 |
(ct[11] & 0xff)) ^ rdk[2];
int t3 = ((ct[12]) << 24 |
(ct[13] & 0xff) << 16 |
(ct[14] & 0xff) << 8 |
(ct[15] & 0xff)) ^ rdk[3];
/*
* Nr - 1 full rounds:
*/
for (int r = 1; r < Nr; r++) {
k += 4;
int a0 =
Td0[(t0 >>> 24)] ^
Td1[(t3 >>> 16) & 0xff] ^
Td2[(t2 >>> 8) & 0xff] ^
Td3[(t1) & 0xff] ^
rdk[k];
int a1 =
Td0[(t1 >>> 24)] ^
Td1[(t0 >>> 16) & 0xff] ^
Td2[(t3 >>> 8) & 0xff] ^
Td3[(t2) & 0xff] ^
rdk[k + 1];
int a2 =
Td0[(t2 >>> 24)] ^
Td1[(t1 >>> 16) & 0xff] ^
Td2[(t0 >>> 8) & 0xff] ^
Td3[(t3) & 0xff] ^
rdk[k + 2];
int a3 =
Td0[(t3 >>> 24)] ^
Td1[(t2 >>> 16) & 0xff] ^
Td2[(t1 >>> 8) & 0xff] ^
Td3[(t0) & 0xff] ^
rdk[k + 3];
t0 = a0;
t1 = a1;
t2 = a2;
t3 = a3;
}
/*
* last round lacks MixColumn:
*/
k += 4;
v = rdk[k];
pt[0] = (byte) (Sd[(t0 >>> 24)] ^ (v >>> 24));
pt[1] = (byte) (Sd[(t3 >>> 16) & 0xff] ^ (v >>> 16));
pt[2] = (byte) (Sd[(t2 >>> 8) & 0xff] ^ (v >>> 8));
pt[3] = (byte) (Sd[(t1) & 0xff] ^ (v));
v = rdk[k + 1];
pt[4] = (byte) (Sd[(t1 >>> 24)] ^ (v >>> 24));
pt[5] = (byte) (Sd[(t0 >>> 16) & 0xff] ^ (v >>> 16));
pt[6] = (byte) (Sd[(t3 >>> 8) & 0xff] ^ (v >>> 8));
pt[7] = (byte) (Sd[(t2) & 0xff] ^ (v));
v = rdk[k + 2];
pt[8] = (byte) (Sd[(t2 >>> 24)] ^ (v >>> 24));
pt[9] = (byte) (Sd[(t1 >>> 16) & 0xff] ^ (v >>> 16));
pt[10] = (byte) (Sd[(t0 >>> 8) & 0xff] ^ (v >>> 8));
pt[11] = (byte) (Sd[(t3) & 0xff] ^ (v));
v = rdk[k + 3];
pt[12] = (byte) (Sd[(t3 >>> 24)] ^ (v >>> 24));
pt[13] = (byte) (Sd[(t2 >>> 16) & 0xff] ^ (v >>> 16));
pt[14] = (byte) (Sd[(t1 >>> 8) & 0xff] ^ (v >>> 8));
pt[15] = (byte) (Sd[(t0) & 0xff] ^ (v));
}
/**
* Destroy all sensitive information in this object.
*/
protected final void finalize() {
if (rek != null) {
for (int i = 0; i < rek.length; i++) {
rek[i] = 0;
}
rek = null;
}
if (rdk != null) {
for (int i = 0; i < rdk.length; i++) {
rdk[i] = 0;
}
rdk = null;
}
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/bip39/ByteUtils.java
================================================
package com.quincysx.crypto.bip39;
/**
* @author QuincySx
* @date 2018/5/15 上午10:34
*/
final class ByteUtils {
static int next11Bits(byte[] bytes, int offset) {
final int skip = offset / 8;
final int lowerBitsToRemove = (3 * 8 - 11) - (offset % 8);
return (((int) bytes[skip] & 0xff) << 16 |
((int) bytes[skip + 1] & 0xff) << 8 |
(lowerBitsToRemove < 8
? ((int) bytes[skip + 2] & 0xff)
: 0)) >> lowerBitsToRemove & (1 << 11) - 1;
}
static void writeNext11(byte[] bytes, int value, int offset) {
int skip = offset / 8;
int bitSkip = offset % 8;
{//byte 0
byte firstValue = bytes[skip];
byte toWrite = (byte) (value >> (3 + bitSkip));
bytes[skip] = (byte) (firstValue | toWrite);
}
{//byte 1
byte valueInByte = bytes[skip + 1];
final int i = 5 - bitSkip;
byte toWrite = (byte) (i > 0 ? (value << i) : (value >> -i));
bytes[skip + 1] = (byte) (valueInByte | toWrite);
}
if (bitSkip >= 6) {//byte 2
byte valueInByte = bytes[skip + 2];
byte toWrite = (byte) (value << 13 - bitSkip);
bytes[skip + 2] = (byte) (valueInByte | toWrite);
}
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/bip39/CharSequenceComparators.java
================================================
package com.quincysx.crypto.bip39;
import java.util.Comparator;
/**
* @author QuincySx
* @date 2018/5/15 上午11:25
*/
enum CharSequenceComparators implements Comparator {
ALPHABETICAL {
@Override
public int compare(final CharSequence o1, final CharSequence o2) {
final int length1 = o1.length();
final int length2 = o2.length();
final int length = Math.min(length1, length2);
for (int i = 0; i < length; i++) {
final int compare = Character.compare(o1.charAt(i), o2.charAt(i));
if (compare != 0) return compare;
}
return Integer.compare(length1, length2);
}
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/bip39/CharSequenceSplitter.java
================================================
package com.quincysx.crypto.bip39;
import java.util.LinkedList;
import java.util.List;
/**
* @author QuincySx
* @date 2018/5/15 上午11:15
*/
final class CharSequenceSplitter {
private final char separator1;
private final char separator2;
CharSequenceSplitter(final char separator1, final char separator2) {
this.separator1 = separator1;
this.separator2 = separator2;
}
List split(final CharSequence charSequence) {
final LinkedList list = new LinkedList<>();
int start = 0;
final int length = charSequence.length();
for (int i = 0; i < length; i++) {
final char c = charSequence.charAt(i);
if (c == separator1 || c == separator2) {
list.add(charSequence.subSequence(start, i));
start = i + 1;
}
}
list.add(charSequence.subSequence(start, length));
return list;
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/bip39/MnemonicGenerator.java
================================================
package com.quincysx.crypto.bip39;
import com.quincysx.crypto.utils.SHA256;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author QuincySx
* @date 2018/5/15 上午10:21
*/
public final class MnemonicGenerator {
private final WordList wordList;
/**
* Create a generator using the given word list.
*
* @param wordList A known ordered list of 2048 words to select from.
*/
public MnemonicGenerator(final WordList wordList) {
this.wordList = wordList;
}
public List createMnemonic(
final CharSequence entropyHex) {
final int length = entropyHex.length();
if (length % 2 == 1)
throw new RuntimeException("Length of hex chars must be divisible by 2");
final byte[] entropy = new byte[length / 2];
try {
for (int i = 0, j = 0; i < length; i += 2, j++) {
entropy[j] = (byte) (parseHex(entropyHex.charAt(i)) << 4 | parseHex(entropyHex.charAt(i + 1)));
}
return createMnemonic(entropy);
} finally {
Arrays.fill(entropy, (byte) 0);
}
}
public List createMnemonic(
final byte[] entropy) {
final int[] wordIndexes = wordIndexes(entropy);
try {
return createMnemonic(wordIndexes);
} finally {
Arrays.fill(wordIndexes, 0);
}
}
private List createMnemonic(
final int[] wordIndexes) {
List mnemonicList = new ArrayList<>();
final String space = String.valueOf(wordList.getSpace());
for (int i = 0; i < wordIndexes.length; i++) {
mnemonicList.add(wordList.getWord(wordIndexes[i]));
}
return mnemonicList;
}
private static int[] wordIndexes(byte[] entropy) {
final int ent = entropy.length * 8;
entropyLengthPreChecks(ent);
final byte[] entropyWithChecksum = Arrays.copyOf(entropy, entropy.length + 1);
entropyWithChecksum[entropy.length] = firstByteOfSha256(entropy);
//checksum length
final int cs = ent / 32;
//mnemonic length
final int ms = (ent + cs) / 11;
//get the indexes into the word list
final int[] wordIndexes = new int[ms];
for (int i = 0, wi = 0; wi < ms; i += 11, wi++) {
wordIndexes[wi] = ByteUtils.next11Bits(entropyWithChecksum, i);
}
return wordIndexes;
}
static byte firstByteOfSha256(final byte[] entropy) {
final byte[] hash = SHA256.sha256(entropy);
final byte firstByte = hash[0];
Arrays.fill(hash, (byte) 0);
return firstByte;
}
private static void entropyLengthPreChecks(final int ent) {
if (ent < 128)
throw new RuntimeException("Entropy too low, 128-256 bits allowed");
if (ent > 256)
throw new RuntimeException("Entropy too high, 128-256 bits allowed");
if (ent % 32 > 0)
throw new RuntimeException("Number of entropy bits must be divisible by 32");
}
private static int parseHex(char c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return (c - 'a') + 10;
if (c >= 'A' && c <= 'F') return (c - 'A') + 10;
throw new RuntimeException("Invalid hex char '" + c + '\'');
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/bip39/MnemonicValidator.java
================================================
package com.quincysx.crypto.bip39;
import com.quincysx.crypto.bip39.validation.InvalidChecksumException;
import com.quincysx.crypto.bip39.validation.InvalidWordCountException;
import com.quincysx.crypto.bip39.validation.UnexpectedWhiteSpaceException;
import com.quincysx.crypto.bip39.validation.WordNotFoundException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
/**
* @author QuincySx
* @date 2018/5/15 上午11:14
*/
public final class MnemonicValidator {
private final WordAndIndex[] words;
private final CharSequenceSplitter charSequenceSplitter;
private final NFKDNormalizer normalizer;
private MnemonicValidator(final WordList wordList) {
normalizer = new WordListMapNormalization(wordList);
words = new WordAndIndex[1 << 11];
for (int i = 0; i < 1 << 11; i++) {
words[i] = new WordAndIndex(i, wordList.getWord(i));
}
charSequenceSplitter = new CharSequenceSplitter(wordList.getSpace(), Normalization.normalizeNFKD(wordList.getSpace()));
Arrays.sort(words, wordListSortOrder);
}
/**
* Get a Mnemonic validator for the given word list.
* No normalization is currently performed, this is an open issue: https://github.com/NovaCrypto/BIP39/issues/13
*
* @param wordList A WordList implementation
* @return A validator
*/
public static MnemonicValidator ofWordList(final WordList wordList) {
return new MnemonicValidator(wordList);
}
/**
* Check that the supplied mnemonic fits the BIP0039 spec.
*
* @param mnemonic The memorable list of words
* @throws InvalidChecksumException If the last bytes don't match the expected last bytes
* @throws InvalidWordCountException If the number of words is not a multiple of 3, 24 or fewer
* @throws WordNotFoundException If a word in the mnemonic is not present in the word list
* @throws UnexpectedWhiteSpaceException Occurs if one of the supplied words is empty, e.g. a double space
*/
public void validate(final CharSequence mnemonic) throws
InvalidChecksumException,
InvalidWordCountException,
WordNotFoundException,
UnexpectedWhiteSpaceException {
validate(charSequenceSplitter.split(mnemonic));
}
/**
* Check that the supplied mnemonic fits the BIP0039 spec.
*
* The purpose of this method overload is to avoid constructing a mnemonic String if you have gathered a list of
* words from the user.
*
* @param mnemonic The memorable list of words
* @throws InvalidChecksumException If the last bytes don't match the expected last bytes
* @throws InvalidWordCountException If the number of words is not a multiple of 3, 24 or fewer
* @throws WordNotFoundException If a word in the mnemonic is not present in the word list
* @throws UnexpectedWhiteSpaceException Occurs if one of the supplied words is empty
*/
public void validate(final Collection extends CharSequence> mnemonic) throws
InvalidChecksumException,
InvalidWordCountException,
WordNotFoundException,
UnexpectedWhiteSpaceException {
final int[] wordIndexes = findWordIndexes(mnemonic);
try {
validate(wordIndexes);
} finally {
Arrays.fill(wordIndexes, 0);
}
}
private static void validate(final int[] wordIndexes) throws
InvalidWordCountException,
InvalidChecksumException {
final int ms = wordIndexes.length;
final int entPlusCs = ms * 11;
final int ent = (entPlusCs * 32) / 33;
final int cs = ent / 32;
if (entPlusCs != ent + cs)
throw new InvalidWordCountException();
// final byte[] entropyWithChecksum = new byte[(entPlusCs + 7) / 8];
//
// wordIndexesToEntropyWithCheckSum(wordIndexes, entropyWithChecksum);
// Arrays.fill(wordIndexes, 0);
//
// final byte[] entropy = Arrays.copyOf(entropyWithChecksum, entropyWithChecksum.length - 1);
// final byte lastByte = entropyWithChecksum[entropyWithChecksum.length - 1];
// Arrays.fill(entropyWithChecksum, (byte) 0);
// final byte sha = MnemonicGenerator.firstByteOfSha256(entropy);
//
// final byte mask = maskOfFirstNBits(cs);
//
// if (((sha ^ lastByte) & mask) != 0)
// throw new InvalidChecksumException();
}
private int[] findWordIndexes(final Collection extends CharSequence> split) throws
UnexpectedWhiteSpaceException,
WordNotFoundException {
final int ms = split.size();
final int[] result = new int[ms];
int i = 0;
for (final CharSequence buffer : split) {
if (buffer.length() == 0) {
throw new UnexpectedWhiteSpaceException();
}
result[i++] = findWordIndex(buffer);
}
return result;
}
private int findWordIndex(final CharSequence buffer) throws WordNotFoundException {
final WordAndIndex key = new WordAndIndex(-1, buffer);
final int index = Arrays.binarySearch(words, key, wordListSortOrder);
if (index < 0) {
final int insertionPoint = -index - 1;
int suggestion = insertionPoint == 0 ? insertionPoint : insertionPoint - 1;
if (suggestion + 1 == words.length) suggestion--;
throw new WordNotFoundException(buffer, words[suggestion].word, words[suggestion + 1].word);
}
return words[index].index;
}
private static void wordIndexesToEntropyWithCheckSum(final int[] wordIndexes, final byte[] entropyWithChecksum) {
for (int i = 0, bi = 0; i < wordIndexes.length; i++, bi += 11) {
ByteUtils.writeNext11(entropyWithChecksum, wordIndexes[i], bi);
}
}
private static byte maskOfFirstNBits(final int n) {
return (byte) ~((1 << (8 - n)) - 1);
}
private static final Comparator wordListSortOrder = new Comparator() {
@Override
public int compare(final WordAndIndex o1, final WordAndIndex o2) {
return CharSequenceComparators.ALPHABETICAL.compare(o1.normalized, o2.normalized);
}
};
private class WordAndIndex {
final CharSequence word;
final String normalized;
final int index;
WordAndIndex(final int i, final CharSequence word) {
this.word = word;
normalized = normalizer.normalize(word);
index = i;
}
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/bip39/NFKDNormalizer.java
================================================
package com.quincysx.crypto.bip39;
/**
* @author QuincySx
* @date 2018/5/15 上午10:41
*/
public interface NFKDNormalizer {
String normalize(CharSequence charSequence);
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/bip39/Normalization.java
================================================
package com.quincysx.crypto.bip39;
import java.text.Normalizer;
/**
* @author QuincySx
* @date 2018/5/15 上午10:40
*/
final class Normalization {
static String normalizeNFKD(final String string) {
return Normalizer.normalize(string, Normalizer.Form.NFKD);
}
static char normalizeNFKD(final char c) {
return normalizeNFKD("" + c).charAt(0);
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/bip39/PBKDF2WithHmacSHA512.java
================================================
package com.quincysx.crypto.bip39;
/**
* @author QuincySx
* @date 2018/5/15 上午10:18
*/
public interface PBKDF2WithHmacSHA512 {
byte[] hash(final char[] chars, final byte[] salt);
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/bip39/RandomSeed.java
================================================
package com.quincysx.crypto.bip39;
import java.security.SecureRandom;
import java.util.Random;
/**
* @author QuincySx
* @date 2018/3/13 上午11:06
*/
public class RandomSeed {
public static byte[] random(WordCount words) {
return random(words, new SecureRandom());
}
public static byte[] random(WordCount words, Random random) {
byte[] randomSeed = new byte[words.byteLength()];
random.nextBytes(randomSeed);
return randomSeed;
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/bip39/SeedCalculator.java
================================================
package com.quincysx.crypto.bip39;
import android.util.Log;
import com.quincysx.crypto.utils.HexUtils;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;
import static com.quincysx.crypto.bip39.Normalization.normalizeNFKD;
/**
* @author QuincySx
* @date 2018/5/15 上午10:38
*/
public final class SeedCalculator {
private final byte[] fixedSalt = getUtf8Bytes("mnemonic");
private final PBKDF2WithHmacSHA512 hashAlgorithm;
public SeedCalculator(final PBKDF2WithHmacSHA512 hashAlgorithm) {
this.hashAlgorithm = hashAlgorithm;
}
/**
* Creates a seed calculator using {@link SpongyCastlePBKDF2WithHmacSHA512} which is the most compatible.
* Use {@link SeedCalculator#SeedCalculator(PBKDF2WithHmacSHA512)} to supply another.
*/
public SeedCalculator() {
this(SpongyCastlePBKDF2WithHmacSHA512.INSTANCE);
}
public byte[] calculateSeed(final List mnemonicList, final String passphrase) {
if (mnemonicList == null || mnemonicList.size() < 3) {
throw new RuntimeException("The dictionary cannot be empty and the number of words must not be less than 3");
}
StringBuilder stringBuilder = new StringBuilder();
for (String str : mnemonicList) {
stringBuilder.append(str).append(" ");
}
String mnemonic = stringBuilder.substring(0, stringBuilder.length() - 1).toString();
return calculateSeed(mnemonic, passphrase);
}
/**
* Calculate the seed given a mnemonic and corresponding passphrase.
* The phrase is not checked for validity here, for that use a {@link MnemonicValidator}.
*
* Due to normalization, these need to be {@link String}, and not {@link CharSequence}, this is an open issue:
* https://github.com/NovaCrypto/BIP39/issues/7
*
* If you have a list of words selected from a word list, you can use {@link #withWordsFromWordList} then
* {@link SeedCalculatorByWordListLookUp#calculateSeed}
*
* @param mnemonic The memorable list of words
* @param passphrase An optional passphrase, use "" if not required
* @return a seed for HD wallet generation
*/
public byte[] calculateSeed(final String mnemonic, final String passphrase) {
final char[] chars = normalizeNFKD(mnemonic).toCharArray();
try {
return calculateSeed(chars, passphrase);
} finally {
Arrays.fill(chars, '\0');
}
}
byte[] calculateSeed(final char[] mnemonicChars, final String passphrase) {
final String normalizedPassphrase = normalizeNFKD(passphrase);
final byte[] salt2 = getUtf8Bytes(normalizedPassphrase);
final byte[] salt = combine(fixedSalt, salt2);
clear(salt2);
final byte[] encoded = hash(mnemonicChars, salt);
clear(salt);
return encoded;
}
public SeedCalculatorByWordListLookUp withWordsFromWordList(final WordList wordList) {
return new SeedCalculatorByWordListLookUp(this, wordList);
}
private static byte[] combine(final byte[] array1, final byte[] array2) {
final byte[] bytes = new byte[array1.length + array2.length];
System.arraycopy(array1, 0, bytes, 0, array1.length);
System.arraycopy(array2, 0, bytes, array1.length, bytes.length - array1.length);
return bytes;
}
private static void clear(final byte[] salt) {
Arrays.fill(salt, (byte) 0);
}
private byte[] hash(final char[] chars, final byte[] salt) {
return hashAlgorithm.hash(chars, salt);
}
private static byte[] getUtf8Bytes(final String string) {
try {
return string.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/bip39/SeedCalculatorByWordListLookUp.java
================================================
package com.quincysx.crypto.bip39;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* @author QuincySx
* @date 2018/5/15 上午10:39
*/
public final class SeedCalculatorByWordListLookUp {
private final SeedCalculator seedCalculator;
private final Map map = new HashMap<>();
private final NFKDNormalizer normalizer;
SeedCalculatorByWordListLookUp(final SeedCalculator seedCalculator, final WordList wordList) {
this.seedCalculator = seedCalculator;
normalizer = new WordListMapNormalization(wordList);
for (int i = 0; i < 1 << 11; i++) {
final String word = normalizer.normalize(wordList.getWord(i));
map.put(word, word.toCharArray());
}
}
/**
* Calculate the seed given a mnemonic and corresponding passphrase.
* The phrase is not checked for validity here, for that use a {@link MnemonicValidator}.
*
* The purpose of this method is to avoid constructing a mnemonic String if you have gathered a list of
* words from the user and also to avoid having to normalize it, all words in the {@link WordList} are normalized
* instead.
*
* Constant 0 is used for external chain.
* External chain is used for addresses that are meant to be visible outside of the wallet (e.g. for receiving
* payments).
*
* @return A {@link Change} = 0 instance for this purpose, coin type and account
*/
public Change external() {
return new Change(this, 0);
}
/**
* Create a {@link Change} for this purpose, coin type and account.
*
* Constant 1 is used for internal chain (also known as change addresses).
* Internal chain is used for addresses which are not meant to be visible outside of the wallet and is used for
* return transaction change.
*
* @return A {@link Change} = 1 instance for this purpose, coin type and account
*/
public Change internal() {
return new Change(this, 1);
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/bip44/AddressIndex.java
================================================
package com.quincysx.crypto.bip44;
import com.quincysx.crypto.bip32.Index;
/**
* @author QuincySx
* @date 2018/3/5 下午4:28
*/
public class AddressIndex {
private final Change change;
private final int addressIndex;
private final boolean isHard;
private final String string;
AddressIndex(final Change change, final int addressIndex) {
this(change, addressIndex, false);
}
AddressIndex(final Change change, final int addressIndex, final boolean head) {
this.change = change;
this.addressIndex = addressIndex;
String s = "%s/%d";
if (head) {
s += "'";
}
string = String.format(s, change, addressIndex);
this.isHard = head;
}
public int getValue() {
if (isHard) {
return Index.hard(addressIndex);
}
return addressIndex;
}
public Change getParent() {
return change;
}
@Override
public String toString() {
return string;
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/bip44/BIP44.java
================================================
package com.quincysx.crypto.bip44;
import android.util.Log;
import com.quincysx.crypto.CoinTypes;
import com.quincysx.crypto.exception.CoinNotFindException;
import com.quincysx.crypto.exception.NonSupportException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author QuincySx
* @date 2018/3/5 下午3:36
*/
public final class BIP44 {
private static final M M = new M();
BIP44() {
}
/**
* Start creating a BIP44 path.
*
* @return A fluent factory for creating BIP44 paths
*/
public static M m() {
return M;
}
public static AddressIndex parsePath(String path) throws NonSupportException,
CoinNotFindException {
// m/44'/60'/0'/0/0
String regEx = "m(/\\d+'?){3}/[0,1]/\\d+'?";
Pattern pattern = Pattern.compile(regEx);
Matcher matcher = pattern.matcher(path);
// 字符串是否与正则表达式相匹配
if (!matcher.matches()) {
throw new NonSupportException("Path format is not correct");
}
String[] split = path.split("/");
String purposeStr = split[1].substring(0, split[1].length() - 1);
String coinTypeStr = split[2].substring(0, split[2].length() - 1);
String accountStr = split[3].substring(0, split[3].length() - 1);
String changeStr = split[4];
String addressStr;
boolean addressHard = false;
if (split[5].contains("'")) {
addressStr = split[5].substring(0, split[5].length() - 1);
addressHard = true;
} else {
addressStr = split[5];
}
if ((Integer.parseInt(purposeStr)) != 44) {
throw new NonSupportException("Only support the 44 protocol");
}
Log.e("++++def", "ddddd " + Integer.parseInt(accountStr));
Account account = BIP44.m()
.purpose44()
.coinType(CoinTypes.parseCoinType(Integer.parseInt(coinTypeStr)))
.account(Integer.parseInt(accountStr));
Change change;
if (Integer.parseInt(changeStr) == 0) {
change = account.external();
} else {
change = account.internal();
}
return change.address(Integer.parseInt(addressStr), addressHard);
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/bip44/Change.java
================================================
package com.quincysx.crypto.bip44;
/**
* @author QuincySx
* @date 2018/3/5 下午4:28
*/
public class Change {
private final Account account;
private final int change;
private final String string;
Change(final Account account, final int change) {
this.account = account;
this.change = change;
string = String.format("%s/%d", account, change);
}
public int getValue() {
return change;
}
public Account getParent() {
return account;
}
@Override
public String toString() {
return string;
}
/**
* Create a {@link AddressIndex} for this purpose, coin type, account and change.
*
* @param addressIndex The index of the child
* @return A coin type instance for this purpose, coin type, account and change.
*/
public AddressIndex address(final int addressIndex) {
return address(addressIndex, false);
}
public AddressIndex address(final int addressIndex, final boolean hard) {
return new AddressIndex(this, addressIndex, hard);
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/bip44/CoinPairDerive.java
================================================
package com.quincysx.crypto.bip44;
import android.util.Log;
import com.quincysx.crypto.CoinTypes;
import com.quincysx.crypto.ECKeyPair;
import com.quincysx.crypto.bip32.ExtendedKey;
import com.quincysx.crypto.bip32.Index;
import com.quincysx.crypto.bip32.ValidationException;
import com.quincysx.crypto.bitcoin.BitCoinECKeyPair;
import com.quincysx.crypto.eos.EOSECKeyPair;
import com.quincysx.crypto.ethereum.EthECKeyPair;
import com.quincysx.crypto.utils.HexUtils;
import com.quincysx.crypto.utils.SHA256;
import org.spongycastle.crypto.digests.MD5Digest;
import org.spongycastle.jcajce.provider.digest.MD5;
import java.util.Map;
import java.util.WeakHashMap;
/**
* @author QuincySx
* @date 2018/3/5 下午3:48
*/
public class CoinPairDerive {
private ExtendedKey mExtendedKey;
public CoinPairDerive(ExtendedKey extendedKey) {
mExtendedKey = extendedKey;
}
public ExtendedKey deriveByExtendedKey(AddressIndex addressIndex) throws ValidationException {
int address = addressIndex.getValue();
int change = addressIndex.getParent().getValue();
int account = addressIndex.getParent().getParent().getValue();
CoinTypes coinType = addressIndex.getParent().getParent().getParent().getValue();
int purpose = addressIndex.getParent().getParent().getParent().getParent().getValue();
ExtendedKey child = mExtendedKey
.getChild(Index.hard(purpose))
.getChild(Index.hard(coinType.coinType()))
.getChild(Index.hard(account))
.getChild(change)
.getChild(address);
return child;
}
public ECKeyPair derive(AddressIndex addressIndex) throws ValidationException {
CoinTypes coinType = addressIndex.getParent().getParent().getParent().getValue();
ExtendedKey child = deriveByExtendedKey(addressIndex);
ECKeyPair ecKeyPair = convertKeyPair(child, coinType);
return ecKeyPair;
}
public ECKeyPair convertKeyPair(ExtendedKey child, CoinTypes coinType) throws ValidationException {
switch (coinType) {
case BitcoinTest:
return BitCoinECKeyPair.parse(child.getMaster(), true);// convertBitcoinKeyPair(new BigInteger(1, child.getMaster().getPrivate()), true);
case Ethereum:
return EthECKeyPair.parse(child.getMaster());//convertEthKeyPair(new BigInteger(1, child.getMaster().getPrivate()));
case EOS:
return EOSECKeyPair.parse(child.getMaster());
case Bitcoin:
default:
return BitCoinECKeyPair.parse(child.getMaster(), false);//convertBitcoinKeyPair(new BigInteger(1, child.getMaster().getPrivate()), false);
}
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/bip44/CoinType.java
================================================
package com.quincysx.crypto.bip44;
import com.quincysx.crypto.CoinTypes;
/**
* @author QuincySx
* @date 2018/3/5 下午4:26
*/
public class CoinType {
private final Purpose purpose;
private final CoinTypes coinType;
private final String string;
CoinType(final Purpose purpose, final CoinTypes coinType) {
this.purpose = purpose;
this.coinType = coinType;
string = String.format("%s/%d'", purpose, coinType.coinType());
}
public CoinTypes getValue() {
return coinType;
}
public Purpose getParent() {
return purpose;
}
@Override
public String toString() {
return string;
}
/**
* Create a {@link Account} for this purpose and coin type.
*
* @param account The account number
* @return An {@link Account} instance for this purpose and coin type
*/
public Account account(final int account) {
return new Account(this, account);
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/bip44/M.java
================================================
package com.quincysx.crypto.bip44;
/**
* @author QuincySx
* @date 2018/3/5 下午4:25
*/
public final class M {
private final Purpose PURPOSE_44 = new Purpose(this, 44);
private final Purpose PURPOSE_49 = new Purpose(this, 49);
M() {
}
/**
* Create a {@link Purpose}.
* For 44 and 49 this function is guaranteed to return the same instance.
*
* @param purpose The purpose number.
* @return A purpose object.
*/
public Purpose purpose(final int purpose) {
switch (purpose) {
case 44:
return PURPOSE_44;
case 49:
return PURPOSE_49;
default:
return new Purpose(this, purpose);
}
}
public Purpose purpose44() {
return PURPOSE_44;
}
public Purpose purpose49() {
return PURPOSE_49;
}
@Override
public String toString() {
return "m";
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/bip44/Purpose.java
================================================
package com.quincysx.crypto.bip44;
import com.quincysx.crypto.CoinTypes;
import com.quincysx.crypto.bip32.Index;
/**
* @author QuincySx
* @date 2018/3/5 下午4:26
*/
public final class Purpose {
private final M m;
private final int purpose;
private final String toString;
Purpose(final M m, final int purpose) {
this.m = m;
if (purpose == 0 || Index.isHardened(purpose))
throw new IllegalArgumentException();
this.purpose = purpose;
toString = String.format("%s/%d'", m, purpose);
}
public int getValue() {
return purpose;
}
@Override
public String toString() {
return toString;
}
/**
* Create a {@link CoinType} for this purpose.
*
* @param coinType The coin type
* @return A coin type instance for this purpose
*/
public CoinType coinType(final CoinTypes coinType) {
return new CoinType(this, coinType);
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/bitcoin/BTCTransaction.java
================================================
/*
The MIT License (MIT)
Copyright (c) 2013 Valentin Konovalov
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/
package com.quincysx.crypto.bitcoin;
import com.quincysx.crypto.ECKeyPair;
import com.quincysx.crypto.Transaction;
import com.quincysx.crypto.bip32.ValidationException;
import com.quincysx.crypto.utils.BTCUtils;
import com.quincysx.crypto.utils.Base58;
import com.quincysx.crypto.utils.HexUtils;
import com.quincysx.crypto.utils.RIPEMD160;
import com.quincysx.crypto.utils.SHA256;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Stack;
@SuppressWarnings("WeakerAccess")
public final class BTCTransaction implements Transaction {
public final int version;
public final Input[] inputs;
public final Output[] outputs;
public final int lockTime;
public BTCTransaction(byte[] rawBytes) throws BitcoinException {
if (rawBytes == null) {
throw new BitcoinException(BitcoinException.ERR_NO_INPUT, "empty input");
}
BitcoinInputStream bais = null;
try {
bais = new BitcoinInputStream(rawBytes);
version = bais.readInt32();
if (version != 1 && version != 2 && version != 3) {
throw new BitcoinException(BitcoinException.ERR_UNSUPPORTED, "Unsupported TX " +
"version", version);
}
int inputsCount = (int) bais.readVarInt();
inputs = new Input[inputsCount];
for (int i = 0; i < inputsCount; i++) {
OutPoint outPoint = new OutPoint(BTCUtils.reverse(bais.readChars(32)), bais
.readInt32());
byte[] script = bais.readChars((int) bais.readVarInt());
int sequence = bais.readInt32();
inputs[i] = new Input(outPoint, new Script(script), sequence);
}
int outputsCount = (int) bais.readVarInt();
outputs = new Output[outputsCount];
for (int i = 0; i < outputsCount; i++) {
long value = bais.readInt64();
long scriptSize = bais.readVarInt();
if (scriptSize < 0 || scriptSize > 10_000_000) {
throw new BitcoinException(BitcoinException.ERR_BAD_FORMAT, "Script size for " +
"output " + i +
" is strange (" + scriptSize + " bytes).");
}
byte[] script = bais.readChars((int) scriptSize);
outputs[i] = new Output(value, new Script(script));
}
lockTime = bais.readInt32();
} catch (EOFException e) {
throw new BitcoinException(BitcoinException.ERR_BAD_FORMAT, "TX incomplete");
} catch (IOException e) {
throw new IllegalArgumentException("Unable to read TX");
} catch (Error e) {
throw new IllegalArgumentException("Unable to read TX: " + e);
} finally {
if (bais != null) {
try {
bais.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public BTCTransaction(Input[] inputs, Output[] outputs, int lockTime) {
this.version = 2;
this.inputs = inputs;
this.outputs = outputs;
this.lockTime = lockTime;
}
@Override
public byte[] getSignBytes() {
return getBytes();
}
public byte[] getBytes() {
BitcoinOutputStream baos = new BitcoinOutputStream();
try {
baos.writeInt32(version);
baos.writeVarInt(inputs.length);
for (Input input : inputs) {
baos.write(BTCUtils.reverse(input.outPoint.hash));
baos.writeInt32(input.outPoint.index);
int scriptLen = input.script == null ? 0 : input.script.bytes.length;
baos.writeVarInt(scriptLen);
if (scriptLen > 0) {
baos.write(input.script.bytes);
}
baos.writeInt32(input.sequence);
}
baos.writeVarInt(outputs.length);
for (Output output : outputs) {
baos.writeInt64(output.value);
int scriptLen = output.script == null ? 0 : output.script.bytes.length;
baos.writeVarInt(scriptLen);
if (scriptLen > 0) {
baos.write(output.script.bytes);
}
}
baos.writeInt32(lockTime);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return baos.toByteArray();
}
@Override
public byte[] getData() {
return new byte[0];
}
@Override
public String toString() {
return "{" +
"\n\"inputs\":\n" + printAsJsonArray(inputs) +
",\n\"outputs\":\n" + printAsJsonArray(outputs) +
",\n\"lockTime\":\"" + lockTime + "\"\n" +
",\n\"version\":\"" + version + "\"}\n";
}
private String printAsJsonArray(Object[] a) {
if (a == null) {
return "null";
}
if (a.length == 0) {
return "[]";
}
int iMax = a.length - 1;
StringBuilder sb = new StringBuilder();
sb.append('[');
for (int i = 0; ; i++) {
sb.append(String.valueOf(a[i]));
if (i == iMax)
return sb.append(']').toString();
sb.append(",\n");
}
}
public static class Input {
public final OutPoint outPoint;
public final Script script;
public final int sequence;
public Input(OutPoint outPoint, Script script, int sequence) {
this.outPoint = outPoint;
this.script = script;
this.sequence = sequence;
}
@Override
public String toString() {
return "{\n\"outPoint\":" + outPoint + ",\n\"script\":\"" + script + "\"," +
"\n\"sequence\":\"" + Integer.toHexString(sequence) + "\"\n}\n";
}
}
public static class OutPoint {
public final byte[] hash;//32-byte hash of the transaction from which we want to redeem
// an output
public final int index;//Four-byte field denoting the output index we want to redeem from
// the transaction with the above hash (output number 2 = output index 1)
public OutPoint(byte[] hash, int index) {
this.hash = hash;
this.index = index;
}
@Override
public String toString() {
return "{" + "\"hash\":\"" + HexUtils.toHex(hash) + "\", \"index\":\"" + index + "\"}";
}
}
public static class Output {
public final long value;
public final Script script;
public Output(long value, Script script) {
this.value = value;
this.script = script;
}
@Override
public String toString() {
return "{\n\"value\":\"" + value * 1e-8 + "\",\"script\":\"" + script + "\"\n}";
}
}
public static final class Script {
public static class ScriptInvalidException extends Exception {
public ScriptInvalidException() {
}
public ScriptInvalidException(String s) {
super(s);
}
}
public static final byte OP_FALSE = 0;
public static final byte OP_TRUE = 0x51;
public static final byte OP_PUSHDATA1 = 0x4c;
public static final byte OP_PUSHDATA2 = 0x4d;
public static final byte OP_PUSHDATA4 = 0x4e;
public static final byte OP_DUP = 0x76;//Duplicates the top stack item.
public static final byte OP_DROP = 0x75;
public static final byte OP_HASH160 = (byte) 0xA9;//The input is hashed twice: first with
// SHA-256 and then with RIPEMD-160.
public static final byte OP_VERIFY = 0x69;//Marks transaction as invalid if top stack
// value is not true. True is removed, but false is not.
public static final byte OP_EQUAL = (byte) 0x87;//Returns 1 if the inputs are exactly
// equal, 0 otherwise.
public static final byte OP_EQUALVERIFY = (byte) 0x88;//Same as OP_EQUAL, but runs
// OP_VERIFY afterward.
public static final byte OP_CHECKSIG = (byte) 0xAC;//The entire transaction's outputs,
// inputs, and script (from the most recently-executed OP_CODESEPARATOR to the end) are
// hashed. The signature used by OP_CHECKSIG must be a valid signature for this hash and
// public key. If it is, 1 is returned, 0 otherwise.
public static final byte OP_CHECKSIGVERIFY = (byte) 0xAD;
public static final byte OP_NOP = 0x61;
public static final byte OP_RETURN = 0x6a;
public static final byte SIGHASH_ALL = 1;
public final byte[] bytes;
public Script(byte[] rawBytes) {
bytes = rawBytes;
}
public Script(byte[] data1, byte[] data2) {
ByteArrayOutputStream baos = new ByteArrayOutputStream(data1.length + data2.length + 2);
try {
writeBytes(data1, baos);
writeBytes(data2, baos);
baos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
bytes = baos.toByteArray();
}
private static void writeBytes(byte[] data, ByteArrayOutputStream baos) throws IOException {
if (data.length < OP_PUSHDATA1) {
baos.write(data.length);
} else if (data.length < 0xff) {
baos.write(OP_PUSHDATA1);
baos.write(data.length);
} else if (data.length < 0xffff) {
// baos.write(OP_PUSHDATA2);
// baos.write(data.length);
baos.write(OP_PUSHDATA2);
baos.write(data.length & 0xff);
baos.write((data.length >> 8) & 0xff);
} else {
// baos.write(OP_PUSHDATA4);
// baos.write(data.length);
baos.write(OP_PUSHDATA4);
baos.write(data.length & 0xff);
baos.write((data.length >> 8) & 0xff);
baos.write((data.length >> 16) & 0xff);
baos.write((data.length >>> 24) & 0xff);
}
baos.write(data);
}
public void run(Stack stack) throws ScriptInvalidException {
run(0, null, stack);
}
public void run(int inputIndex, BTCTransaction tx, Stack stack) throws
ScriptInvalidException {
for (int pos = 0; pos < bytes.length; pos++) {
switch (bytes[pos]) {
case OP_NOP:
break;
case OP_DROP:
if (stack.isEmpty()) {
throw new IllegalArgumentException("stack empty on OP_DROP");
}
stack.pop();
break;
case OP_DUP:
if (stack.isEmpty()) {
throw new IllegalArgumentException("stack empty on OP_DUP");
}
stack.push(stack.peek());
break;
case OP_HASH160:
if (stack.isEmpty()) {
throw new IllegalArgumentException("stack empty on OP_HASH160");
}
stack.push(RIPEMD160.hash160(stack.pop()));
break;
case OP_EQUAL:
case OP_EQUALVERIFY:
if (stack.size() < 2) {
throw new IllegalArgumentException("not enough elements to perform " +
"OP_EQUAL");
}
stack.push(new byte[]{(byte) (Arrays.equals(stack.pop(), stack.pop()) ? 1
: 0)});
if (bytes[pos] == OP_EQUALVERIFY) {
if (verifyFails(stack)) {
throw new ScriptInvalidException("wrong address");
}
}
break;
case OP_VERIFY:
if (verifyFails(stack)) {
throw new ScriptInvalidException();
}
break;
case OP_CHECKSIG:
case OP_CHECKSIGVERIFY:
byte[] publicKey = stack.pop();
byte[] signatureAndHashType = stack.pop();
if (signatureAndHashType[signatureAndHashType.length - 1] != SIGHASH_ALL) {
throw new IllegalArgumentException("I cannot check this sig type: " +
signatureAndHashType[signatureAndHashType.length - 1]);
}
byte[] signature = new byte[signatureAndHashType.length - 1];
System.arraycopy(signatureAndHashType, 0, signature, 0, signature.length);
byte[] hash = hashTransaction(inputIndex, bytes, tx);
boolean valid = BTCUtils.verify(publicKey, signature, hash);
if (bytes[pos] == OP_CHECKSIG) {
stack.push(new byte[]{(byte) (valid ? 1 : 0)});
} else {
if (verifyFails(stack)) {
throw new ScriptInvalidException("Bad signature");
}
if (!stack.empty()) {
throw new ScriptInvalidException("Bad signature - superfluous " +
"scriptSig operations");
}
}
break;
case OP_FALSE:
stack.push(new byte[]{0});
break;
case OP_TRUE:
stack.push(new byte[]{1});
break;
default:
int op = bytes[pos] & 0xff;
int len;
if (op < OP_PUSHDATA1) {
len = op;
byte[] data = new byte[len];
System.arraycopy(bytes, pos + 1, data, 0, len);
stack.push(data);
pos += data.length;
} else if (op == OP_PUSHDATA1) {
len = bytes[pos + 1] & 0xff;
byte[] data = new byte[len];
System.arraycopy(bytes, pos + 1, data, 0, len);
stack.push(data);
pos += 1 + data.length;
} else {
throw new IllegalArgumentException("I cannot read this data: " +
Integer.toHexString(bytes[pos]));
}
break;
}
}
}
public static byte[] hashTransaction(int inputIndex, byte[] subscript, BTCTransaction tx) {
Input[] unsignedInputs = new Input[tx.inputs.length];
for (int i = 0; i < tx.inputs.length; i++) {
Input txInput = tx.inputs[i];
if (i == inputIndex) {
unsignedInputs[i] = new Input(txInput.outPoint, new Script(subscript),
txInput.sequence);
} else {
unsignedInputs[i] = new Input(txInput.outPoint, new Script(new byte[0]),
txInput.sequence);
}
}
BTCTransaction unsignedTransaction = new BTCTransaction(unsignedInputs, tx.outputs,
tx.lockTime);
return hashTransactionForSigning(unsignedTransaction);
}
public static byte[] hashTransactionForSigning(BTCTransaction unsignedTransaction) {
byte[] txUnsignedBytes = unsignedTransaction.getSignBytes();
BitcoinOutputStream baos = new BitcoinOutputStream();
try {
baos.write(txUnsignedBytes);
baos.writeInt32(BTCTransaction.Script.SIGHASH_ALL);
baos.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
return SHA256.doubleSha256(baos.toByteArray());
}
public static boolean verifyFails(Stack stack) {
byte[] input;
boolean valid;
input = stack.pop();
if (input.length == 0 || (input.length == 1 && input[0] == OP_FALSE)) {
//false
stack.push(new byte[]{OP_FALSE});
valid = false;
} else {
//true
valid = true;
}
return !valid;
}
@Override
public String toString() {
return convertBytesToReadableString(bytes);
}
//converts something like "OP_DUP OP_HASH160 ba507bae8f1643d2556000ca26b9301b9069dc6b
// OP_EQUALVERIFY OP_CHECKSIG" into bytes
public static byte[] convertReadableStringToBytes(String readableString) {
String[] tokens = readableString.trim().split("\\s+");
ByteArrayOutputStream os = new ByteArrayOutputStream();
for (String token : tokens) {
switch (token) {
case "OP_NOP":
os.write(OP_NOP);
break;
case "OP_DROP":
os.write(OP_DROP);
break;
case "OP_DUP":
os.write(OP_DUP);
break;
case "OP_HASH160":
os.write(OP_HASH160);
break;
case "OP_EQUAL":
os.write(OP_EQUAL);
break;
case "OP_EQUALVERIFY":
os.write(OP_EQUALVERIFY);
break;
case "OP_VERIFY":
os.write(OP_VERIFY);
break;
case "OP_CHECKSIG":
os.write(OP_CHECKSIG);
break;
case "OP_CHECKSIGVERIFY":
os.write(OP_CHECKSIGVERIFY);
break;
case "OP_FALSE":
os.write(OP_FALSE);
break;
case "OP_TRUE":
os.write(OP_TRUE);
break;
default:
if (token.startsWith("OP_")) {
throw new IllegalArgumentException("I don't know this operation: " +
token);
}
byte[] data = HexUtils.fromHex(token);
if (data == null) {
throw new IllegalArgumentException("I don't know what's this: " +
token);
}
if (data.length < OP_PUSHDATA1) {
os.write(data.length);
try {
os.write(data);
} catch (IOException e) {
throw new RuntimeException("ByteArrayOutputStream behaves weird: " +
"" + e);
}
} else if (data.length <= 255) {
os.write(OP_PUSHDATA1);
os.write(data.length);
try {
os.write(data);
} catch (IOException e) {
throw new RuntimeException("ByteArrayOutputStream behaves weird: " +
"" + e);
}
} else {
throw new IllegalArgumentException("OP_PUSHDATA2 & OP_PUSHDATA4 are " +
"not supported");
}
break;
}
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
return os.toByteArray();
}
public static String convertBytesToReadableString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int pos = 0; pos < bytes.length; pos++) {
if (sb.length() > 0) {
sb.append(' ');
}
switch (bytes[pos]) {
case OP_NOP:
sb.append("OP_NOP");
break;
case OP_DROP:
sb.append("OP_DROP");
break;
case OP_DUP:
sb.append("OP_DUP");
break;
case OP_HASH160:
sb.append("OP_HASH160");
break;
case OP_EQUAL:
sb.append("OP_EQUAL");
break;
case OP_EQUALVERIFY:
sb.append("OP_EQUALVERIFY");
break;
case OP_VERIFY:
sb.append("OP_VERIFY");
break;
case OP_CHECKSIG:
sb.append("OP_CHECKSIG");
break;
case OP_CHECKSIGVERIFY:
sb.append("OP_CHECKSIGVERIFY");
break;
case OP_FALSE:
sb.append("OP_FALSE");
break;
case OP_TRUE:
sb.append("OP_TRUE");
break;
default:
int op = bytes[pos] & 0xff;
int len;
if (op < OP_PUSHDATA1) {
len = op;
byte[] data = new byte[len];
System.arraycopy(bytes, pos + 1, data, 0, len);
sb.append(HexUtils.toHex(data));
pos += data.length;
} else if (op == OP_PUSHDATA1) {
len = bytes[pos + 1] & 0xff;
byte[] data = new byte[len];
System.arraycopy(bytes, pos + 1, data, 0, len);//FIXME I suspect
// there is off by one error...
sb.append(HexUtils.toHex(data));
pos += 1 + data.length;
} else {
throw new IllegalArgumentException("I cannot read this data: " +
Integer.toHexString(bytes[pos]) + " at " + pos);
}
break;
}
}
return sb.toString();
}
@Override
public boolean equals(Object o) {
return this == o || !(o == null || getClass() != o.getClass()) && Arrays.equals
(bytes, ((Script) o).bytes);
}
@Override
public int hashCode() {
return Arrays.hashCode(bytes);
}
public static Script buildOutput(String address) throws BitcoinException {
//noinspection TryWithIdenticalCatches
try {
byte[] addressWithCheckSumAndNetworkCode = Base58.decode(address);
if (addressWithCheckSumAndNetworkCode[0] != 0
&& addressWithCheckSumAndNetworkCode[0] != 111
&& addressWithCheckSumAndNetworkCode[0] != 5) {
throw new BitcoinException(BitcoinException.ERR_UNSUPPORTED, "Unknown address" +
" type", address);
}
byte[] bareAddress = new byte[20];
System.arraycopy(addressWithCheckSumAndNetworkCode, 1, bareAddress, 0,
bareAddress.length);
MessageDigest digestSha = MessageDigest.getInstance("SHA-256");
digestSha.update(addressWithCheckSumAndNetworkCode, 0,
addressWithCheckSumAndNetworkCode.length - 4);
byte[] calculatedDigest = digestSha.digest(digestSha.digest());
for (int i = 0; i < 4; i++) {
if (calculatedDigest[i] !=
addressWithCheckSumAndNetworkCode[addressWithCheckSumAndNetworkCode
.length - 4 + i]) {
throw new BitcoinException(BitcoinException.ERR_BAD_FORMAT, "Bad " +
"address", address);
}
}
if (addressWithCheckSumAndNetworkCode[0] == 5) {
//P2SH 的锁定脚本
ByteArrayOutputStream buf = new ByteArrayOutputStream();
buf.write(OP_HASH160);
writeBytes(bareAddress, buf);
buf.write(OP_EQUAL);
return new Script(buf.toByteArray());
} else {
//P2PKH 的锁定脚本
ByteArrayOutputStream buf = new ByteArrayOutputStream(25);
buf.write(OP_DUP);
buf.write(OP_HASH160);
writeBytes(bareAddress, buf);
buf.write(OP_EQUALVERIFY);
buf.write(OP_CHECKSIG);
return new Script(buf.toByteArray());
}
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@Override
public byte[] sign(ECKeyPair key) throws ValidationException {
BTCTransaction sign = key.sign(this.getSignBytes());
int length = sign.inputs.length;
for (int i = 0; i < length; i++) {
this.inputs[i] = sign.inputs[i];
}
// return sign.getSignBytes();
return getSignBytes();
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/bitcoin/BitCoinECKeyPair.java
================================================
package com.quincysx.crypto.bitcoin;
import com.quincysx.crypto.ECKeyPair;
import com.quincysx.crypto.Key;
import com.quincysx.crypto.bip32.ValidationException;
import com.quincysx.crypto.utils.Base58;
import com.quincysx.crypto.utils.Base58Check;
import com.quincysx.crypto.utils.HexUtils;
import com.quincysx.crypto.utils.RIPEMD160;
import com.quincysx.crypto.utils.SHA256;
import org.spongycastle.asn1.ASN1Integer;
import org.spongycastle.asn1.DERInteger;
import org.spongycastle.asn1.DERSequenceGenerator;
import org.spongycastle.crypto.digests.SHA256Digest;
import org.spongycastle.crypto.params.ECPrivateKeyParameters;
import org.spongycastle.crypto.params.ParametersWithRandom;
import org.spongycastle.crypto.signers.ECDSASigner;
import org.spongycastle.crypto.signers.HMacDSAKCalculator;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;
/**
* @author QuincySx
* @date 2018/3/8 上午10:56
*/
public class BitCoinECKeyPair extends ECKeyPair {
private static final int TEST_NET_ADDRESS_SUFFIX = 0x6f;
private static final int MAIN_NET_ADDRESS_SUFFIX = 0x00;
public static final int MAIN_NET_PRIVATE_KEY_PREFIX = 0x80;
public static final int TEST_NET_PRIVATE_KEY_PREFIX = 0xef;
private static final int MAIN_NET_PRIVATE_KEY_SUFFIX = 0x01;
private static final int RAW_PRIVATE_KEY_COMPRESSED_LENGTH = 38;
private static final int RAW_PRIVATE_KEY_NO_COMPRESSED_LENGTH = 37;
private final boolean testNet;
public static BitCoinECKeyPair parse(Key keyPair, boolean testNet) {
return new BitCoinECKeyPair(keyPair, testNet);
}
public static BitCoinECKeyPair parseWIF(String wif) throws ValidationException {
byte[] decode = Base58.decode(wif);
//判断私钥格式
byte[] check = new byte[4];
System.arraycopy(decode, decode.length - 4, check, 0, check.length);
byte[] privateCheck = SHA256.doubleSha256(decode, 0, decode.length - 4);
for (int i = 0; i < 4; i++) {
if (check[i] != privateCheck[i]) {
throw new ValidationException("WIF Private Key Incorrect format");
}
}
boolean isCompressed = false;
if (decode.length == RAW_PRIVATE_KEY_COMPRESSED_LENGTH) {
isCompressed = true;
}
boolean isTestNet = false;
if ((decode[0] & 0xFF) == TEST_NET_PRIVATE_KEY_PREFIX) {
isTestNet = true;
}
byte[] bytes = new byte[32];
System.arraycopy(decode, 1, bytes, 0, bytes.length);
return new BitCoinECKeyPair(bytes, isTestNet, isCompressed);
}
public BitCoinECKeyPair(byte[] p, boolean testNet, boolean compressed) throws
ValidationException {
super(p, compressed);
this.testNet = testNet;
}
public BitCoinECKeyPair(BigInteger priv, boolean testNet, boolean compressed) {
super(priv, compressed);
this.testNet = testNet;
}
public BitCoinECKeyPair(Key keyPair, boolean testNet) {
super(keyPair);
this.testNet = testNet;
}
protected BitCoinECKeyPair(BigInteger priv, boolean compressed) throws ValidationException {
super(priv, compressed);
this.testNet = false;
}
public boolean isTestNet() {
return testNet;
}
@Override
public String getPrivateKey() {
byte[] bytes = getRawPrivateKey();
byte[] rawPrivateKey = new byte[isCompressed() ? RAW_PRIVATE_KEY_COMPRESSED_LENGTH :
RAW_PRIVATE_KEY_NO_COMPRESSED_LENGTH];
System.arraycopy(bytes, 0, rawPrivateKey, 1, bytes.length);
rawPrivateKey[0] = (byte) (isTestNet() ? TEST_NET_PRIVATE_KEY_PREFIX :
MAIN_NET_PRIVATE_KEY_PREFIX);
if (isCompressed()) {
rawPrivateKey[rawPrivateKey.length - 5] = MAIN_NET_PRIVATE_KEY_SUFFIX;
}
byte[] check = SHA256.doubleSha256(rawPrivateKey, 0, rawPrivateKey.length - 4);
System.arraycopy(check, 0, rawPrivateKey, rawPrivateKey.length - 4, 4);
return Base58.encode(rawPrivateKey);
}
@Override
public String getPublicKey() {
return HexUtils.toHex(getRawPublicKey());
}
@Override
public String getAddress() {
return Base58.encode(getRawAddress());
}
@Override
public byte[] getRawPublicKey() {
return getRawPublicKey(isCompressed());
}
@Override
public byte[] getRawAddress() {
byte[] hashedPublicKey;
//进行 Sha256 Ripemd160 运算
if (isCompressed()) {
hashedPublicKey = RIPEMD160.hash160(pubComp);
} else {
hashedPublicKey = RIPEMD160.hash160(pub);
}
byte[] addressBytes = new byte[1 + hashedPublicKey.length + 4];
//拼接测试网络或正式网络前缀
addressBytes[0] = (byte) (testNet ? TEST_NET_ADDRESS_SUFFIX : MAIN_NET_ADDRESS_SUFFIX);
System.arraycopy(hashedPublicKey, 0, addressBytes, 1, hashedPublicKey.length);
//进行双 Sha256 运算
byte[] check = SHA256.doubleSha256(addressBytes, 0, addressBytes.length - 4);
//将双 Sha256 运算的结果前 4位 拼接到尾部
System.arraycopy(check, 0, addressBytes, hashedPublicKey.length + 1, 4);
Arrays.fill(hashedPublicKey, (byte) 0);
Arrays.fill(check, (byte) 0);
return addressBytes;
}
@Override
public BTCTransaction sign(byte[] messageHash) throws ValidationException {
try {
BTCTransaction btcTransaction = new BTCTransaction(messageHash);
return signTransaction(btcTransaction, priv, getRawPublicKey(), getAddress());
} catch (BitcoinException e) {
e.printStackTrace();
throw new ValidationException(e);
}
}
public byte[] signBTC(byte[] hash) {
ECDSASigner signer = new ECDSASigner();
signer.init(true, new ECPrivateKeyParameters(priv, domain));
BigInteger[] signature = signer.generateSignature(hash);
ByteArrayOutputStream s = new ByteArrayOutputStream();
try {
DERSequenceGenerator seq = new DERSequenceGenerator(s);
seq.addObject(new DERInteger(signature[0]));
seq.addObject(new DERInteger(signature[1]));
seq.close();
return s.toByteArray();
} catch (IOException e) {
}
return null;
}
public boolean verifyBTC(byte[] hash, byte[] signature) {
return verify(hash, signature, pubComp);
}
private static void checkChecksum(byte[] store) throws ValidationException {
byte[] checksum = new byte[4];
System.arraycopy(store, store.length - 4, checksum, 0, 4);
byte[] ekey = new byte[store.length - 4];
System.arraycopy(store, 0, ekey, 0, store.length - 4);
byte[] hash = SHA256.doubleSha256(ekey);
for (int i = 0; i < 4; ++i) {
if (hash[i] != checksum[i]) {
throw new ValidationException("checksum mismatch");
}
}
}
public static BTCTransaction signTransaction(BTCTransaction transaction, BigInteger
privateKeyBigInteger, byte[] publicKey, String address) {
BTCTransaction.Input[] signedInput = new BTCTransaction.Input[transaction.inputs.length];
for (int i = 0; i < transaction.inputs.length; i++) {
signedInput[i] = sign(transaction, i, privateKeyBigInteger, publicKey, address,
BTCTransaction.Script.SIGHASH_ALL);
}
return new BTCTransaction(signedInput, transaction.outputs, transaction.lockTime);
}
/**
* 对单个Input进行签名
*
* @param transaction 交易
* @param index Input索引
* @reture 签名完毕的Input
*/
public static BTCTransaction.Input sign(BTCTransaction transaction, int index, BigInteger
privateKeyBigInteger, byte[] publicKey, String address, byte ScriptType) {
String publicScript = mkPubKeyScript(address);
//清空无关Input的Script,对相关Script进行签名
signatureForm(transaction, index, publicScript);
//双 Sha256 and 签名
byte[] signature = sign(privateKeyBigInteger, BTCTransaction.Script
.hashTransactionForSigning(transaction));
//拼版本
byte[] signatureAndHashType = new byte[signature.length + 1];
System.arraycopy(signature, 0, signatureAndHashType, 0, signature.length);
signatureAndHashType[signatureAndHashType.length - 1] = ScriptType;
//拼出新的input
return new BTCTransaction.Input(transaction.inputs[index].outPoint, new BTCTransaction
.Script(signatureAndHashType, publicKey), transaction.inputs[index].sequence);
}
/**
* 设置Input的地址签名
*
* @param transaction 交易
* @param index 索引
* @param publicScript 地址签名
* @return 新的交易
*/
private static BTCTransaction signatureForm(BTCTransaction transaction, int index, String
publicScript) {
//存放清空地址签名的Input
for (int i = 0; i < transaction.inputs.length; i++) {
BTCTransaction.Script script = null;
if (i == index) {
//设置地址签名
script = new BTCTransaction.Script(HexUtils.fromHex(publicScript));
}
transaction.inputs[i] = new BTCTransaction.Input(transaction.inputs[i].outPoint,
script, transaction.inputs[i].sequence);
}
return transaction;
}
/**
* 签署地址签名
*
* @param address 地址
* @return 签名
*/
private static String mkPubKeyScript(String address) {
//设置加密格式
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("76a914");
//设置签名
byte[] bytes = Base58Check.base58ToBytes(address);
byte[] checkByte = new byte[bytes.length - 1];
System.arraycopy(bytes, 1, checkByte, 0, checkByte.length);
stringBuilder.append(HexUtils.toHex(checkByte));
Arrays.fill(bytes, (byte) 0);
Arrays.fill(checkByte, (byte) 0);
//设置签名后缀格式
stringBuilder.append("88ac");
return stringBuilder.toString();
}
public static byte[] sign(BigInteger privateKey, byte[] input) {
synchronized (domain) {
ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
ECPrivateKeyParameters privateKeyParam = new ECPrivateKeyParameters(privateKey, domain);
signer.init(true, new ParametersWithRandom(privateKeyParam, secureRandom));
BigInteger[] sign = signer.generateSignature(input);
BigInteger r = sign[0];
BigInteger s = sign[1];
BigInteger largestAllowedS = new BigInteger
("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0", 16);
//SECP256K1_N_DIV_2
if (s.compareTo(largestAllowedS) > 0) {
//https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki#low-s-values-in
// -signatures
s = LARGEST_PRIVATE_KEY.subtract(s);
}
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream(72);
DERSequenceGenerator derGen = new DERSequenceGenerator(baos);
derGen.addObject(new ASN1Integer(r));
derGen.addObject(new ASN1Integer(s));
derGen.close();
return baos.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/bitcoin/BitcoinException.java
================================================
/*
The MIT License (MIT)
Copyright (c) 2013-2014 Valentin Konovalov
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/
package com.quincysx.crypto.bitcoin;
@SuppressWarnings("WeakerAccess")
public final class BitcoinException extends Exception {
public static final int ERR_NO_SPENDABLE_OUTPUTS_FOR_THE_ADDRESS = 0;
public static final int ERR_INSUFFICIENT_FUNDS = 1;
public static final int ERR_WRONG_TYPE = 2;
public static final int ERR_BAD_FORMAT = 3;
public static final int ERR_INCORRECT_PASSWORD = 4;
public static final int ERR_MEANINGLESS_OPERATION = 5;
public static final int ERR_NO_INPUT = 6;
public static final int ERR_FEE_IS_TOO_BIG = 7;
public static final int ERR_FEE_IS_LESS_THEN_ZERO = 8;
public static final int ERR_CHANGE_IS_LESS_THEN_ZERO = 9;
public static final int ERR_AMOUNT_TO_SEND_IS_LESS_THEN_ZERO = 10;
public static final int ERR_UNSUPPORTED = 11;
public final int errorCode;
@SuppressWarnings({"WeakerAccess", "unused"})
public final Object extraInformation;
public BitcoinException(int errorCode, String detailMessage, Object extraInformation) {
super(detailMessage);
this.errorCode = errorCode;
this.extraInformation = extraInformation;
}
public BitcoinException(int errorCode, String detailMessage) {
this(errorCode, detailMessage, null);
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/bitcoin/BitcoinInputStream.java
================================================
/*
The MIT License (MIT)
Copyright (c) 2013 Valentin Konovalov
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/
package com.quincysx.crypto.bitcoin;
import java.io.ByteArrayInputStream;
import java.io.EOFException;
import java.io.IOException;
@SuppressWarnings("WeakerAccess")
public class BitcoinInputStream extends ByteArrayInputStream {
public BitcoinInputStream(byte[] buf) {
super(buf);
}
@SuppressWarnings("unused")
public BitcoinInputStream(byte[] buf, int offset, int length) {
super(buf, offset, length);
}
public int readInt16() throws EOFException {
return (readByte() & 0xff) | ((readByte() & 0xff) << 8);
}
public int readInt32() throws EOFException {
return (readByte() & 0xff) | ((readByte() & 0xff) << 8) | ((readByte() & 0xff) << 16) | ((readByte() & 0xff) << 24);
}
public long readInt64() throws EOFException {
return (readInt32() & 0xFFFFFFFFL )| ((readInt32() & 0xFFFFFFFFL) << 32);
}
public int readByte() throws EOFException {
int readedByte = super.read();
if (readedByte == -1) {
throw new EOFException();
}
return readedByte;
}
public long readVarInt() throws EOFException {
int readedByte = readByte();
if (readedByte < 0xfd) {
return readedByte;
} else if (readedByte == 0xfd) {
return readInt16();
} else if (readedByte == 0xfe) {
return readInt32();
} else {
return readInt64();
}
}
public byte[] readChars(final int count) throws IOException {
byte[] buf = new byte[count];
int off = 0;
while (off != count) {
int bytesReadCurr = read(buf, off, count - off);
if (bytesReadCurr == -1) {
throw new EOFException();
} else {
off += bytesReadCurr;
}
}
return buf;
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/bitcoin/BitcoinOutputStream.java
================================================
/*
The MIT License (MIT)
Copyright (c) 2013 Valentin Konovalov
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/
package com.quincysx.crypto.bitcoin;
import java.io.ByteArrayOutputStream;
@SuppressWarnings("WeakerAccess")
public final class BitcoinOutputStream extends ByteArrayOutputStream {
public void writeInt16(int value) {
write(value & 0xff);
write((value >> 8) & 0xff);
}
public void writeInt32(int value) {
write(value & 0xff);
write((value >> 8) & 0xff);
write((value >> 16) & 0xff);
write((value >>> 24) & 0xff);
}
public void writeInt64(long value) {
writeInt32((int) (value & 0xFFFFFFFFL));
writeInt32((int) ((value >>> 32) & 0xFFFFFFFFL));
}
public void writeVarInt(long value) {
if (value < 0xfd) {
write((int) (value & 0xff));
} else if (value < 0xffff) {
write(0xfd);
writeInt16((int) value);
} else if (value < 0xffffffffL) {
write(0xfe);
writeInt32((int) value);
} else {
write(0xff);
writeInt64(value);
}
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/eip55/EthCheckAddress.java
================================================
package com.quincysx.crypto.eip55;
import com.quincysx.crypto.utils.HexUtils;
import com.quincysx.crypto.utils.KECCAK256;
/**
* @author QuincySx
* @date 2018/6/20 下午5:39
*/
public class EthCheckAddress {
/**
* 生成 Checksum 的地址
*
* @param address 普通地址
* @return Checksum 地址
*/
public static String toChecksumAddress(String address) {
String lowercaseAddress = cleanHexPrefix(address).toLowerCase();
String addressHash = (HexUtils.toHex(KECCAK256.keccak256(lowercaseAddress.getBytes())));
StringBuilder result = new StringBuilder(lowercaseAddress.length() + 2);
if (containsHexPrefix(address)) {
result.append("0x");
}
for (int i = 0; i < lowercaseAddress.length(); i++) {
if (Integer.parseInt(String.valueOf(addressHash.charAt(i)), 16) >= 8) {
result.append(String.valueOf(lowercaseAddress.charAt(i)).toUpperCase());
} else {
result.append(lowercaseAddress.charAt(i));
}
}
return result.toString();
}
/**
* 检查 ETH 地址是否合法
*
* @param address ETH 地址
* @return true:合法 false:不合法
*/
public static boolean checksumAddress(String address) {
if (!containsHexPrefix(address)) {
//没有前缀 0x
return false;
} else if (checkUppercase(cleanHexPrefix(address))) {
String checksumAddress = toChecksumAddress(address);
if (checksumAddress.equals(address)) {
return true;
}
return false;
} else {
return true;
}
}
/**
* 检查字符串中是否有大写英文字母
*
* @param address ETH 地址
* @return true:大写 false:小写
*/
private static boolean checkUppercase(String address) {
for (int i = 0; i < address.length(); i++) {
char c = address.charAt(i);
if (Character.isUpperCase(c)) {
return true;
}
}
return false;
}
/**
* 如果字符串 0x 开头则去掉
*
* @param input 要处理的字符串
* @return 处理完成的字符串
*/
public static String cleanHexPrefix(String input) {
if (containsHexPrefix(input)) {
return input.substring(2);
} else {
return input;
}
}
/**
* 检查字符串是否是 0x 开头
*
* @param input 要检测的字符串
* @return true:0x 开头 false:不是 0x 开头
*/
public static boolean containsHexPrefix(String input) {
return !isEmpty(input) && input.length() > 1
&& input.charAt(0) == '0' && input.charAt(1) == 'x';
}
private static boolean isEmpty(String s) {
return s == null || s.length() == 0;
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/eos/EOSECKeyPair.java
================================================
package com.quincysx.crypto.eos;
import com.quincysx.crypto.ECKeyPair;
import com.quincysx.crypto.Key;
import com.quincysx.crypto.bip32.ValidationException;
import com.quincysx.crypto.utils.Base58;
import com.quincysx.crypto.utils.KECCAK256;
import com.quincysx.crypto.utils.RIPEMD160;
import com.quincysx.crypto.utils.SHA256;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.Arrays;
/**
* @author QuincySx
* @date 2018/6/13 上午11:28
*/
public class EOSECKeyPair extends ECKeyPair {
public static final String address_prefix = "EOS";
public static final int PRIVATE_KEY_PREFIX = 0x80;
public static EOSECKeyPair parse(Key keyPair) {
return new EOSECKeyPair(keyPair);
}
public static EOSECKeyPair parse(String privateKey) throws ValidationException {
byte[] decode = Base58.decode(privateKey);
byte[] checksum = SHA256.doubleSha256(decode, 0, decode.length - 4);
for (int i = 0; i < 4; i++) {
if (decode[decode.length - 4 + i] != checksum[i]) {
throw new ValidationException("私钥验证失败");
}
}
byte[] key = new byte[decode.length - 5];
System.arraycopy(decode, 1, key, 0, key.length);
BigInteger integer = new BigInteger(1, key);
Arrays.fill(key, (byte) 0);
Arrays.fill(decode, (byte) 0);
Arrays.fill(checksum, (byte) 0);
return new EOSECKeyPair(integer);
}
public EOSECKeyPair(byte[] p) throws ValidationException {
super(p, true);
}
public EOSECKeyPair(BigInteger priv) {
super(priv, true);
}
public EOSECKeyPair(Key keyPair) {
super(keyPair);
}
@Override
public byte[] getRawPrivateKey() {
return super.getRawPrivateKey();
}
@Override
public String getPrivateKey() {
byte[] rawPrivateKey = getRawPrivateKey();
byte[] privateKey = new byte[rawPrivateKey.length + 5];
privateKey[0] = (byte) PRIVATE_KEY_PREFIX;
System.arraycopy(rawPrivateKey, 0, privateKey, 1, rawPrivateKey.length);
byte[] checksum = SHA256.doubleSha256(privateKey, 0, privateKey.length - 4);
System.arraycopy(checksum, 0, privateKey, rawPrivateKey.length + 1, 4);
Arrays.fill(checksum, (byte) 0);
Arrays.fill(rawPrivateKey, (byte) 0);
return Base58.encode(privateKey);
}
@Override
public byte[] getRawPublicKey() {
byte[] publicKey = new byte[pubComp.length];
System.arraycopy(pubComp, 0, publicKey, 0, publicKey.length);
return publicKey;
}
@Override
public String getPublicKey() {
byte[] rawPublicKey = getRawPublicKey();
byte[] publicKey = new byte[rawPublicKey.length + 4];
System.arraycopy(rawPublicKey, 0, publicKey, 0, rawPublicKey.length);
byte[] bytes = RIPEMD160.ripemd160(rawPublicKey);
System.arraycopy(bytes, 0, publicKey, rawPublicKey.length, 4);
StringBuffer bf = new StringBuffer(address_prefix);
bf.append(Base58.encode(publicKey));
Arrays.fill(rawPublicKey, (byte) 0);
Arrays.fill(publicKey, (byte) 0);
Arrays.fill(bytes, (byte) 0);
return bf.toString();
}
@Override
public byte[] getRawAddress() {
byte[] byteAddress = KECCAK256.keccak256(getRawPublicKey());
byte[] address = new byte[20];
System.arraycopy(byteAddress, 12, address, 0, address.length);
return address;
}
@Override
public String getAddress() {
return getPublicKey();
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/ethereum/Bloom.java
================================================
/*
* Copyright (c) [2016] [ ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see .
*/
package com.quincysx.crypto.ethereum;
import com.quincysx.crypto.ethereum.utils.ByteUtil;
import org.spongycastle.util.encoders.Hex;
import java.util.Arrays;
/**
* See http://www.herongyang.com/Java/Bit-String-Set-Bit-to-Byte-Array.html.
*
* @author Roman Mandeleil
* @since 20.11.2014
*/
public class Bloom {
final static int _8STEPS = 8;
final static int _3LOW_BITS = 7;
final static int ENSURE_BYTE = 255;
byte[] data = new byte[256];
public Bloom() {
}
public Bloom(byte[] data) {
this.data = data;
}
public static Bloom create(byte[] toBloom) {
int mov1 = (((toBloom[0] & ENSURE_BYTE) & (_3LOW_BITS)) << _8STEPS) + ((toBloom[1]) & ENSURE_BYTE);
int mov2 = (((toBloom[2] & ENSURE_BYTE) & (_3LOW_BITS)) << _8STEPS) + ((toBloom[3]) & ENSURE_BYTE);
int mov3 = (((toBloom[4] & ENSURE_BYTE) & (_3LOW_BITS)) << _8STEPS) + ((toBloom[5]) & ENSURE_BYTE);
byte[] data = new byte[256];
Bloom bloom = new Bloom(data);
ByteUtil.setBit(data, mov1, 1);
ByteUtil.setBit(data, mov2, 1);
ByteUtil.setBit(data, mov3, 1);
return bloom;
}
public void or(Bloom bloom) {
for (int i = 0; i < data.length; ++i) {
data[i] |= bloom.data[i];
}
}
public boolean matches(Bloom topicBloom) {
Bloom copy = copy();
copy.or(topicBloom);
return this.equals(copy);
}
public byte[] getData() {
return data;
}
public Bloom copy() {
return new Bloom(Arrays.copyOf(getData(), getData().length));
}
@Override
public String toString() {
return Hex.toHexString(data);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Bloom bloom = (Bloom) o;
return Arrays.equals(data, bloom.data);
}
@Override
public int hashCode() {
return data != null ? Arrays.hashCode(data) : 0;
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/ethereum/ByteArrayWrapper.java
================================================
/*
* Copyright (c) [2016] [ ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see .
*/
package com.quincysx.crypto.ethereum;
import com.quincysx.crypto.ethereum.utils.FastByteComparisons;
import org.spongycastle.util.encoders.Hex;
import java.io.Serializable;
import java.util.Arrays;
/**
* @author Roman Mandeleil
* @since 11.06.2014
*/
public class ByteArrayWrapper implements Comparable, Serializable {
private final byte[] data;
private int hashCode = 0;
public ByteArrayWrapper(byte[] data) {
if (data == null)
throw new NullPointerException("Data must not be null");
this.data = data;
this.hashCode = Arrays.hashCode(data);
}
public boolean equals(Object other) {
if (!(other instanceof ByteArrayWrapper))
return false;
byte[] otherData = ((ByteArrayWrapper) other).getData();
return FastByteComparisons.compareTo(
data, 0, data.length,
otherData, 0, otherData.length) == 0;
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public int compareTo(ByteArrayWrapper o) {
return FastByteComparisons.compareTo(
data, 0, data.length,
o.getData(), 0, o.getData().length);
}
public byte[] getData() {
return data;
}
@Override
public String toString() {
return Hex.toHexString(data);
}
}
================================================
FILE: library/src/main/java/com/quincysx/crypto/ethereum/CallTransaction.java
================================================
/*
* Copyright (c) [2016] [ ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see .
*/
package com.quincysx.crypto.ethereum;
import static com.quincysx.crypto.ethereum.utils.ByteUtil.longToBytesNoLeadZeroes;
import static java.lang.String.format;
import static com.quincysx.crypto.ethereum.solidity.SolidityType.IntType;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.quincysx.crypto.ethereum.solidity.SolidityType;
import com.quincysx.crypto.ethereum.utils.ByteUtil;
import com.quincysx.crypto.ethereum.utils.FastByteComparisons;
import com.quincysx.crypto.ethereum.vm.LogInfo;
import com.quincysx.crypto.utils.KECCAK256;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import org.spongycastle.pqc.math.linearalgebra.ByteUtils;
import org.spongycastle.util.BigIntegers;
import org.spongycastle.util.encoders.Hex;
/**
* Creates a contract function call transaction.
* Serializes arguments according to the function ABI .
*
* Created by Anton Nashatyrev on 25.08.2015.
*/
public class CallTransaction {
private final static ObjectMapper DEFAULT_MAPPER = new ObjectMapper()
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL);
public static EthTransaction createRawTransaction(BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, String toAddress,
BigInteger value, byte[] data) {
EthTransaction tx = new EthTransaction(BigIntegers.asUnsignedByteArray(nonce),
BigIntegers.asUnsignedByteArray(gasPrice),
BigIntegers.asUnsignedByteArray(gasLimit),
toAddress == null ? null : Hex.decode(toAddress),
BigIntegers.asUnsignedByteArray(value),
data,
null);
return tx;
}
/**
* 创建交易
*
* @param nonce nonce
* @param gasPrice gasPrice
* @param gasLimit gasLimit
* @param toAddress toAddress
* @param value value
* @param callFunc 调用合约方法
* @param funcArgs 合约参数(Int 数值请使用BigInteger或字符串)
* @return 交易
*/
public static EthTransaction createCallTransaction(BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, String toAddress,
BigInteger value, Function callFunc, Object... funcArgs) {
byte[] callData = callFunc.encode(funcArgs);
return createRawTransaction(nonce, gasPrice, gasLimit, toAddress, value, callData);
}
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class Param {
public Boolean indexed;
public String name;
public SolidityType type;
@JsonGetter("type")
public String getType() {
return type.getName();
}
}
public enum FunctionType {
constructor,
function,
event,
fallback
}
public static class Function {
public boolean anonymous;
public boolean constant;
public boolean payable;
public String name = "";
public Param[] inputs = new Param[0];
public Param[] outputs = new Param[0];
public FunctionType type;
private Function() {
}
public byte[] encode(Object... args) {
return ByteUtil.merge(encodeSignature(), encodeArguments(args));
}
public byte[] encodeArguments(Object... args) {
if (args.length > inputs.length)
throw new RuntimeException("Too many arguments: " + args.length + " > " + inputs.length);
int staticSize = 0;
int dynamicCnt = 0;
// calculating static size and number of dynamic params
for (int i = 0; i < args.length; i++) {
Param param = inputs[i];
if (param.type.isDynamicType()) {
dynamicCnt++;
}
staticSize += param.type.getFixedSize();
}
byte[][] bb = new byte[args.length + dynamicCnt][];
int curDynamicPtr = staticSize;
int curDynamicCnt = 0;
for (int i = 0; i < args.length; i++) {
if (inputs[i].type.isDynamicType()) {
byte[] dynBB = inputs[i].type.encode(args[i]);
bb[i] = SolidityType.IntType.encodeInt(curDynamicPtr);
bb[args.length + curDynamicCnt] = dynBB;
curDynamicCnt++;
curDynamicPtr += dynBB.length;
} else {
bb[i] = inputs[i].type.encode(args[i]);
}
}
return ByteUtil.merge(bb);
}
private Object[] decode(byte[] encoded, Param[] params) {
Object[] ret = new Object[params.length];
int off = 0;
for (int i = 0; i < params.length; i++) {
if (params[i].type.isDynamicType()) {
ret[i] = params[i].type.decode(encoded, IntType.decodeInt(encoded, off).intValue());
} else {
ret[i] = params[i].type.decode(encoded, off);
}
off += params[i].type.getFixedSize();
}
return ret;
}
public Object[] decode(byte[] encoded) {
//import static org.apache.commons.lang3.ArrayUtils.subarray;
//return decode(subarray(encoded, 4, encoded.length), inputs);
return decode(ByteUtils.subArray(encoded, 4, encoded.length), inputs);
}
public Object[] decodeResult(byte[] encodedRet) {
return decode(encodedRet, outputs);
}
public String formatSignature() {
StringBuilder paramsTypes = new StringBuilder();
for (Param param : inputs) {
paramsTypes.append(param.type.getCanonicalName()).append(",");
}
//import static org.apache.commons.lang3.StringUtils.stripEnd;
//return format("%s(%s)", name, stripEnd(paramsTypes.toString(), ","));
return format("%s(%s)", name, stripEnd(paramsTypes.toString(), ","));
}
public static String stripEnd(final String str, final String stripChars) {
int end;
if (str == null || (end = str.length()) == 0) {
return str;
}
if (stripChars == null) {
while (end != 0 && Character.isWhitespace(str.charAt(end - 1))) {
end--;
}
} else if (stripChars.isEmpty()) {
return str;
} else {
while (end != 0 && stripChars.indexOf(str.charAt(end - 1)) != -1) {
end--;
}
}
return str.substring(0, end);
}
public byte[] encodeSignatureLong() {
String signature = formatSignature();
// byte[] sha3Fingerprint = sha3(signature.getSignBytes());
byte[] sha3Fingerprint = KECCAK256.keccak256(signature.getBytes());
return sha3Fingerprint;
}
public byte[] encodeSignature() {
return Arrays.copyOfRange(encodeSignatureLong(), 0, 4);
}
@Override
public String toString() {
return formatSignature();
}
public static Function fromJsonInterface(String json) {
try {
return DEFAULT_MAPPER.readValue(json, Function.class);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static Function fromSignature(String funcName, String... paramTypes) {
return fromSignature(funcName, paramTypes, new String[0]);
}
public static Function fromSignature(String funcName, String[] paramTypes, String[] resultTypes) {
Function ret = new Function();
ret.name = funcName;
ret.constant = false;
ret.type = FunctionType.function;
ret.inputs = new Param[paramTypes.length];
for (int i = 0; i < paramTypes.length; i++) {
ret.inputs[i] = new Param();
ret.inputs[i].name = "param" + i;
ret.inputs[i].type = SolidityType.getType(paramTypes[i]);
}
ret.outputs = new Param[resultTypes.length];
for (int i = 0; i < resultTypes.length; i++) {
ret.outputs[i] = new Param();
ret.outputs[i].name = "res" + i;
ret.outputs[i].type = SolidityType.getType(resultTypes[i]);
}
return ret;
}
}
public static class Contract {
public Contract(String jsonInterface) {
try {
functions = new ObjectMapper().readValue(jsonInterface, Function[].class);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public Function getByName(String name) {
for (Function function : functions) {
if (name.equals(function.name)) {
return function;
}
}
return null;
}
public Function getConstructor() {
for (Function function : functions) {
if (function.type == FunctionType.constructor) {
return function;
}
}
return null;
}
private Function getBySignatureHash(byte[] hash) {
if (hash.length == 4) {
for (Function function : functions) {
if (FastByteComparisons.equal(function.encodeSignature(), hash)) {
return function;
}
}
} else if (hash.length == 32) {
for (Function function : functions) {
if (FastByteComparisons.equal(function.encodeSignatureLong(), hash)) {
return function;
}
}
} else {
throw new RuntimeException("Function signature hash should be 4 or 32 bytes length");
}
return null;
}
/**
* Parses function and its arguments from transaction invocation binary data
*/
public Invocation parseInvocation(byte[] data) {
if (data.length < 4) throw new RuntimeException("Invalid data length: " + data.length);
Function function = getBySignatureHash(Arrays.copyOfRange(data, 0, 4));
if (function == null)
throw new RuntimeException("Can't find function/event by it signature");
Object[] args = function.decode(data);
return new Invocation(this, function, args);
}
/**
* Parses Solidity Event and its data members from transaction receipt LogInfo
*/
public Invocation parseEvent(LogInfo eventLog) {
Function event = getBySignatureHash(eventLog.getTopics().get(0).getData());
int indexedArg = 1;
if (event == null) return null;
List