1665129937
A minimal ethereum javascript wallet.
LightWallet is a HD wallet that can store your private keys encrypted in the browser to allow you to run Ethereum dapps even if you're not running a local Ethereum node. It uses BIP32 and BIP39 to generate an HD tree of addresses from a randomly generated 12-word seed.
LightWallet is primarily intended to be a signing provider for the Hooked Web3 provider through the keystore
module. This allows you to have full control over your private keys while still connecting to a remote node to relay signed transactions. Moreover, the txutils
functions can be used to construct transactions when offline, for use in e.g. air-gapped coldwallet implementations.
The default BIP32 HD derivation path has been m/0'/0'/0'/i
, but any HD path can be chosen.
Please note that LightWallet has not been through a comprehensive security review at this point. It is still experimental software, intended for small amounts of Ether to be used for interacting with smart contracts on the Ethereum blockchain. Do not rely on it to store larger amounts of Ether yet.
npm install eth-lightwallet
The eth-lightwallet
package contains dist/lightwallet.min.js
that can be included in an HTML page:
<html>
<body>
<script src="lightwallet.min.js"></script>
</body>
</html>
The file lightwallet.min.js
exposes the global object lightwallet
to the browser which has the two main modules lightwallet.keystore
and lightwallet.txutils
.
Sample recommended usage with hooked web3 provider:
// the seed is stored encrypted by a user-defined password
var password = prompt('Enter password for encryption', 'password');
keyStore.createVault({
password: password,
// seedPhrase: seedPhrase, // Optionally provide a 12-word seed phrase
// salt: fixture.salt, // Optionally provide a salt.
// A unique salt will be generated otherwise.
// hdPathString: hdPath // Optional custom HD Path String
}, function (err, ks) {
// Some methods will require providing the `pwDerivedKey`,
// Allowing you to only decrypt private keys on an as-needed basis.
// You can generate that value with this convenient method:
ks.keyFromPassword(password, function (err, pwDerivedKey) {
if (err) throw err;
// generate five new address/private key pairs
// the corresponding private keys are also encrypted
ks.generateNewAddress(pwDerivedKey, 5);
var addr = ks.getAddresses();
ks.passwordProvider = function (callback) {
var pw = prompt("Please enter password", "Password");
callback(null, pw);
};
// Now set ks as transaction_signer in the hooked web3 provider
// and you can start using web3 using the keys/addresses in ks!
});
});
Sample old-style usage with hooked web3 provider (still works, but less secure because uses fixed salts).
// generate a new BIP32 12-word seed
var secretSeed = lightwallet.keystore.generateRandomSeed();
// the seed is stored encrypted by a user-defined password
var password = prompt('Enter password for encryption', 'password');
lightwallet.keystore.deriveKeyFromPassword(password, function (err, pwDerivedKey) {
var ks = new lightwallet.keystore(secretSeed, pwDerivedKey);
// generate five new address/private key pairs
// the corresponding private keys are also encrypted
ks.generateNewAddress(pwDerivedKey, 5);
var addr = ks.getAddresses();
// Create a custom passwordProvider to prompt the user to enter their
// password whenever the hooked web3 provider issues a sendTransaction
// call.
ks.passwordProvider = function (callback) {
var pw = prompt("Please enter password", "Password");
callback(null, pw);
};
// Now set ks as transaction_signer in the hooked web3 provider
// and you can start using web3 using the keys/addresses in ks!
});
keystore
Function definitionsThese are the interface functions for the keystore object. The keystore object holds a 12-word seed according to BIP39 spec. From this seed you can generate addresses and private keys, and use the private keys to sign transactions.
Note: Addresses and RLP encoded data are in the form of hex-strings. Hex-strings start with 0x
.
keystore.createVault(options, callback)
This is the interface to create a new lightwallet keystore.
BIP39
compliant HD Path String. Previously the default has been m/0'/0'/0'
, another popular one is the BIP44 path string m/44'/60'/0'/0
.keystore.keyFromPassword(password, callback)
This instance method uses any internally-configured salt to return the appropriate pwDerivedKey
.
Takes the user's password as input and generates a symmetric key of type Uint8Array
that is used to encrypt/decrypt the keystore.
keystore.isDerivedKeyCorrect(pwDerivedKey)
Returns true
if the derived key can decrypt the seed, and returns false
otherwise.
keystore.generateRandomSeed([extraEntropy])
Generates a string consisting of a random 12-word seed and returns it. If the optional argument string extraEntropy
is present the random data from the Javascript RNG will be concatenated with extraEntropy
and then hashed to produce the final seed. The string extraEntropy
can be something like entropy from mouse movements or keyboard presses, or a string representing dice throws.
keystore.isSeedValid(seed)
Checks if seed
is a valid 12-word seed according to the BIP39 specification.
keystore.generateNewAddress(pwDerivedKey, [num])
Allows the vault to generate additional internal address/private key pairs.
The simplest usage is ks.generateNewAddress(pwDerivedKey)
.
Generates num
new address/private key pairs (defaults to 1) in the keystore from the seed phrase, which will be returned with calls to ks.getAddresses()
.
keystore.deserialize(serialized_keystore)
Takes a serialized keystore string serialized_keystore
and returns a new keystore object.
keystore.serialize()
Serializes the current keystore object into a JSON-encoded string and returns that string.
keystore.getAddresses()
Returns a list of hex-string addresses currently stored in the keystore.
keystore.getSeed(pwDerivedKey)
Given the pwDerivedKey, decrypts and returns the users 12-word seed.
keystore.exportPrivateKey(address, pwDerivedKey)
Given the derived key, decrypts and returns the private key corresponding to address
. This should be done sparingly as the recommended practice is for the keystore
to sign transactions using signing.signTx
, so there is normally no need to export private keys.
upgrade
Function definitionskeystore.upgradeOldSerialized(oldSerialized, password, callback)
Takes a serialized keystore in an old format and a password. The callback takes the upgraded serialized keystore as its second argument.
signing
Function definitionssigning.signTx(keystore, pwDerivedKey, rawTx, signingAddress, hdPathString)
Signs a transaction with the private key corresponding to signingAddress
.
keystore
: An instance of the keystore with which to sign the TX with.pwDerivedKey
: the users password derived key (Uint8Array)rawTx
: Hex-string defining an RLP-encoded raw transaction.signingAddress
: hex-string defining the address to send the transaction from.hdPathString
: (Optional) A path at which to create the encryption keys.Hex-string corresponding to the RLP-encoded raw transaction.
signing.signMsg(keystore, pwDerivedKey, rawMsg, signingAddress, hdPathString)
Creates and signs a sha3 hash of a message with the private key corresponding to signingAddress
.
keystore
: An instance of the keystore with which to sign the TX with.pwDerivedKey
: the users password derived key (Uint8Array)rawMsg
: Message to be signedsigningAddress
: hex-string defining the address corresponding to the signing private key.hdPathString
: (Optional) A path at which to create the encryption keys.Signed hash as signature object with v, r and s values.
signing.signMsgHash(keystore, pwDerivedKey, msgHash, signingAddress, hdPathString)
Signs a sha3 message hash with the private key corresponding to signingAddress
.
keystore
: An instance of the keystore with which to sign the TX with.pwDerivedKey
: the users password derived key (Uint8Array)msgHash
: SHA3 hash to be signedsigningAddress
: hex-string defining the address corresponding to the signing private key.hdPathString
: (Optional) A path at which to create the encryption keys.Signed hash as signature object with v, r and s values.
signing.concatSig(signature)
Concatenates signature object to return signature as hex-string in the same format as eth_sign
does.
signature
: Signature object as returned from signMsg
or ``signMsgHash`.Concatenated signature object as hex-string.
signing.recoverAddress(rawMsg, v, r, s)
Recovers the signing address from the message rawMsg
and the signature v, r, s
.
encryption
Function definitionsencryption.multiEncryptString(keystore, pwDerivedKey, msg, myAddress, theirPubKeyArray)
NOTE: The format of encrypted messages has not been finalized and may change at any time, so only use this for ephemeral messages that do not need to be stored encrypted for a long time.
Encrypts the string msg
with a randomly generated symmetric key, then encrypts that symmetric key assymetrically to each of the pubkeys in theirPubKeyArray
. The encrypted message can then be read only by sender and the holders of the private keys corresponding to the public keys in theirPubKeyArray
. The returned object has the following form, where nonces and ciphertexts are encoded in base64:
{ version: 1,
asymAlg: 'curve25519-xsalsa20-poly1305',
symAlg: 'xsalsa20-poly1305',
symNonce: 'SLmxcH3/CPMCCJ7orkI7iSjetRlMmzQH',
symEncMessage: 'iN4+/b5InlsVo5Bc7GTmaBh8SgWV8OBMHKHMVf7aq5O9eqwnIzVXeX4yzUWbw2w=',
encryptedSymKey:
[ { nonce: 'qcNCtKqiooYLlRuIrNlNVtF8zftoT5Cb',
ciphertext: 'L8c12EJsFYM1K7udgHDRrdHhQ7ng+VMkzOdVFTjWu0jmUzpehFeqyoEyg8cROBmm' },
{ nonce: 'puD2x3wmQKu3OIyxgJq2kG2Hz01+dxXs',
ciphertext: 'gLYtYpJbeFKXL/WAK0hyyGEelaL5Ddq9BU3249+hdZZ7xgTAZVL8tw+fIVcvpgaZ' },
{ nonce: '1g8VbftPnjc+1NG3zCGwZS8KO73yjucu',
ciphertext: 'pftERJOPDV2dfP+C2vOwPWT43Q89V74Nfu1arNQeTMphSHqVuUXItbyCMizISTxG' },
{ nonce: 'KAH+cCxbFGSDjHDOBzDhMboQdFWepvBw',
ciphertext: 'XWmmBmxLEyLTUmUBiWy2wDqedubsa0KTcufhKM7YfJn/eHWhDDptMxYDvaKisFmn' } ] }
Note that no padding is applied to msg
, so it's possible to deduce the length of the string msg
from the ciphertext. If you don't want this information to be known, please apply padding to msg
before calling this function.
encryption.multiDecryptString(keystore, pwDerivedKey, encMsg, theirPubKey, myAddress)
Decrypt a message encMsg
created with the function multiEncryptString()
. If successful, returns the original message string. If not successful, returns false
.
encryption.addressToPublicEncKey(keystore, pwDerivedKey, address)
Gets the public encryption key corresponding to the private key of address
in the keystore
.
txutils
Function definitionsThese are the interface functions for the txutils
module. These functions will create RLP encoded raw unsigned transactions which can be signed using the keystore.signTx()
command.
txutils.createContractTx(fromAddress, txObject)
Using the data in txObject
, creates an RLP-encoded transaction that will create the contract with compiled bytecode defined by txObject.data
. Also computes the address of the created contract.
fromAddress
: Address to send the transaction fromtxObject.gasLimit
: Gas limittxObject.gasPrice
: Gas pricetxObject.value
: Endowment (optional)txObject.nonce
: Nonce of fromAddress
txObject.data
: Compiled code of the contractObject obj
with fields
obj.tx
: RLP encoded transaction (hex string)obj.addr
: Address of the created contracttxutils.functionTx(abi, functionName, args, txObject)
Creates a transaction calling a function with name functionName
, with arguments args
conforming to abi
. The function is defined in a contract with address txObject.to
.
abi
: Json-formatted ABI as returned from the solc
compilerfunctionName
: string with the function nameargs
: Array with the arguments to the functiontxObject.to
: Address of the contracttxObject.gasLimit
: Gas limittxObject.gasPrice
: Gas pricetxObject.value
: Value to sendtxObject.nonce
: Nonce of sending addressRLP-encoded hex string defining the transaction.
txutils.valueTx(txObject)
Creates a transaction sending value to txObject.to
.
txObject.to
: Address to send totxObject.gasLimit
: Gas limittxObject.gasPrice
: Gas pricetxObject.value
: Value to sendtxObject.nonce
: Nonce of sending addressRLP-encoded hex string defining the transaction.
See the file example_usage.js
for usage of keystore
and txutils
in node.
See the file example_web.html
for an example of how to use the LightWallet keystore together with the Hooked Web3 Provider in the browser.
Run all tests:
npm run test
npm run coverage
Author: ConsenSys
Download Link: Download The Source Code
Official Website: https://github.com/ConsenSys/eth-lightwallet
License: MIT license
#javascript #blockchain #ethereum
1651163100
PDFKit
A JavaScript PDF generation library for Node and the browser.
PDFKit is a PDF document generation library for Node and the browser that makes creating complex, multi-page, printable documents easy. The API embraces chainability, and includes both low level functions as well as abstractions for higher level functionality. The PDFKit API is designed to be simple, so generating complex documents is often as simple as a few function calls.
Check out some of the documentation and examples to see for yourself! You can also read the guide as a self-generated PDF with example output displayed inline. If you'd like to see how it was generated, check out the README in the docs folder.
You can also try out an interactive in-browser demo of PDFKit here.
Installation uses the npm package manager. Just type the following command after installing npm.
npm install pdfkit
const PDFDocument = require('pdfkit');
const fs = require('fs');
// Create a document
const doc = new PDFDocument();
// Pipe its output somewhere, like to a file or HTTP response
// See below for browser usage
doc.pipe(fs.createWriteStream('output.pdf'));
// Embed a font, set the font size, and render some text
doc
.font('fonts/PalatinoBold.ttf')
.fontSize(25)
.text('Some text with an embedded font!', 100, 100);
// Add an image, constrain it to a given size, and center it vertically and horizontally
doc.image('path/to/image.png', {
fit: [250, 300],
align: 'center',
valign: 'center'
});
// Add another page
doc
.addPage()
.fontSize(25)
.text('Here is some vector graphics...', 100, 100);
// Draw a triangle
doc
.save()
.moveTo(100, 150)
.lineTo(100, 250)
.lineTo(200, 250)
.fill('#FF3300');
// Apply some transforms and render an SVG path with the 'even-odd' fill rule
doc
.scale(0.6)
.translate(470, -380)
.path('M 250,75 L 323,301 131,161 369,161 177,301 z')
.fill('red', 'even-odd')
.restore();
// Add some text with annotations
doc
.addPage()
.fillColor('blue')
.text('Here is a link!', 100, 100)
.underline(100, 100, 160, 27, { color: '#0000FF' })
.link(100, 100, 160, 27, 'http://google.com/');
// Finalize PDF file
doc.end();
The PDF output from this example (with a few additions) shows the power of PDFKit — producing complex documents with a very small amount of code. For more, see the demo
folder and the PDFKit programming guide.
There are three ways to use PDFKit in the browser:
pdfkit.standalone.js
file in the releases or in the package js
folder.In addition to PDFKit, you'll need somewhere to stream the output to. HTML5 has a Blob object which can be used to store binary data, and get URLs to this data in order to display PDF output inside an iframe, or upload to a server, etc. In order to get a Blob from the output of PDFKit, you can use the blob-stream module.
The following example uses Browserify or webpack to load PDFKit
and blob-stream
. See here and here for examples of prebuilt version usage.
// require dependencies
const PDFDocument = require('pdfkit');
const blobStream = require('blob-stream');
// create a document the same way as above
const doc = new PDFDocument();
// pipe the document to a blob
const stream = doc.pipe(blobStream());
// add your content to the document here, as usual
// get a blob when you are done
doc.end();
stream.on('finish', function() {
// get a blob you can do whatever you like with
const blob = stream.toBlob('application/pdf');
// or get a blob URL for display in the browser
const url = stream.toBlobURL('application/pdf');
iframe.src = url;
});
You can see an interactive in-browser demo of PDFKit here.
Note that in order to Browserify a project using PDFKit, you need to install the brfs
module with npm, which is used to load built-in font data into the package. It is listed as a devDependency
in PDFKit's package.json
, so it isn't installed by default for Node users. If you forget to install it, Browserify will print an error message.
For complete API documentation and more examples, see the PDFKit website.
Author: foliojs
Source Code: https://github.com/foliojs/pdfkit
License: MIT License
1664968620
A JavaScript TrueType font engine for modern browsers and Node.js.
work in progress...
sfnt version | Implemented |
---|---|
numTables | Implemented |
searchRange | Implemented |
entrySelector | Implemented |
rangeShift | Implemented |
Table Directory | Implemented |
---|
cmap | Part Implemented |
---|---|
glyf | Almost |
head | Almost |
hhea | - |
hmtx | - |
loca | Almost |
maxp | Almost |
name | - |
post | - |
OS/2 | - |
cvt | - |
---|---|
EBDT | - |
EBLC | - |
EBSC | - |
fpgm | - |
gasp | - |
hdmx | - |
kern | - |
LTSH | - |
prep | - |
PCLT | - |
VDMX | - |
vhea | - |
vmtx | - |
Author: Ynakajima
Source Code: https://github.com/ynakajima/ttf.js
1664980260
zlib port to javascript, very fast!
Why pako is cool:
This project was done to understand how fast JS can be and is it necessary to develop native C modules for CPU-intensive tasks. Enjoy the result!
Benchmarks:
node v12.16.3 (zlib 1.2.9), 1mb input sample:
deflate-imaya x 4.75 ops/sec ±4.93% (15 runs sampled)
deflate-pako x 10.38 ops/sec ±0.37% (29 runs sampled)
deflate-zlib x 17.74 ops/sec ±0.77% (46 runs sampled)
gzip-pako x 8.86 ops/sec ±1.41% (29 runs sampled)
inflate-imaya x 107 ops/sec ±0.69% (77 runs sampled)
inflate-pako x 131 ops/sec ±1.74% (82 runs sampled)
inflate-zlib x 258 ops/sec ±0.66% (88 runs sampled)
ungzip-pako x 115 ops/sec ±1.92% (80 runs sampled)
node v14.15.0 (google's zlib), 1mb output sample:
deflate-imaya x 4.93 ops/sec ±3.09% (16 runs sampled)
deflate-pako x 10.22 ops/sec ±0.33% (29 runs sampled)
deflate-zlib x 18.48 ops/sec ±0.24% (48 runs sampled)
gzip-pako x 10.16 ops/sec ±0.25% (28 runs sampled)
inflate-imaya x 110 ops/sec ±0.41% (77 runs sampled)
inflate-pako x 134 ops/sec ±0.66% (83 runs sampled)
inflate-zlib x 402 ops/sec ±0.74% (87 runs sampled)
ungzip-pako x 113 ops/sec ±0.62% (80 runs sampled)
zlib's test is partially affected by marshalling (that make sense for inflate only). You can change deflate level to 0 in benchmark source, to investigate details. For deflate level 6 results can be considered as correct.
Install:
npm install pako
Full docs - http://nodeca.github.io/pako/
const pako = require('pako');
// Deflate
//
const input = new Uint8Array();
//... fill input data here
const output = pako.deflate(input);
// Inflate (simple wrapper can throw exception on broken stream)
//
const compressed = new Uint8Array();
//... fill data to uncompress here
try {
const result = pako.inflate(compressed);
// ... continue processing
} catch (err) {
console.log(err);
}
//
// Alternate interface for chunking & without exceptions
//
const deflator = new pako.Deflate();
deflator.push(chunk1, false);
deflator.push(chunk2); // second param is false by default.
...
deflator.push(chunk_last, true); // `true` says this chunk is last
if (deflator.err) {
console.log(deflator.msg);
}
const output = deflator.result;
const inflator = new pako.Inflate();
inflator.push(chunk1);
inflator.push(chunk2);
...
inflator.push(chunk_last); // no second param because end is auto-detected
if (inflator.err) {
console.log(inflator.msg);
}
const output = inflator.result;
Sometime you can wish to work with strings. For example, to send stringified objects to server. Pako's deflate detects input data type, and automatically recode strings to utf-8 prior to compress. Inflate has special option, to say compressed data has utf-8 encoding and should be recoded to javascript's utf-16.
const pako = require('pako');
const test = { my: 'super', puper: [456, 567], awesome: 'pako' };
const compressed = pako.deflate(JSON.stringify(test));
const restored = JSON.parse(pako.inflate(compressed, { to: 'string' }));
Pako does not contain some specific zlib functions:
deflateCopy
, deflateBound
, deflateParams
, deflatePending
, deflatePrime
, deflateTune
.inflateCopy
, inflateMark
, inflatePrime
, inflateGetDictionary
, inflateSync
, inflateSyncPoint
, inflateUndermine
.Available as part of the Tidelift Subscription
The maintainers of pako and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.
Personal thanks to:
Original implementation (in C):
Author: Nodeca
Source Code: https://github.com/nodeca/pako
License: MIT license
1622207074
Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.
JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.
JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.
Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.
In JavaScript, ‘document.write‘ is used to represent a string on a browser.
<script type="text/javascript">
document.write("Hello World!");
</script>
<script type="text/javascript">
//single line comment
/* document.write("Hello"); */
</script>
#javascript #javascript code #javascript hello world #what is javascript #who invented javascript
1616670795
It is said that a digital resource a business has must be interactive in nature, so the website or the business app should be interactive. How do you make the app interactive? With the use of JavaScript.
Does your business need an interactive website or app?
Hire Dedicated JavaScript Developer from WebClues Infotech as the developer we offer is highly skilled and expert in what they do. Our developers are collaborative in nature and work with complete transparency with the customers.
The technology used to develop the overall app by the developers from WebClues Infotech is at par with the latest available technology.
Get your business app with JavaScript
For more inquiry click here https://bit.ly/31eZyDZ
Book Free Interview: https://bit.ly/3dDShFg
#hire dedicated javascript developers #hire javascript developers #top javascript developers for hire #hire javascript developer #hire a freelancer for javascript developer #hire the best javascript developers