How do I create an HD wallet and child wallets in Solana? - solana

I know how to make a wallet in Solana:
const keypair = solanaWeb3.Keypair.fromSeed(seed);
Similar to 'what is a HD wallet for Ether and how to create one using nodejs?'
I'd like to create an HD wallet using Solana.
Specifically, I have created a keypair and would like to create a child keypair. I can't find any references to creating HD wallets in the Solana Cookbook.
But how do I make child wallets? Here's what I'd do in Ethereum:
var mnemonic = "seed sock milk ...";
var path = "m/44'/60'/0'/0/0";
var hdwallet = hdkey.fromMasterSeed(bip39.mnemonicToSeed(mnemonic));
var wallet = hdwallet.derivePath(path).getWallet();
How do I create an HD wallet and child wallets in Solana?

You can use the BIP-44 derivePath helper for this purpose. From the Solana cookbook:
import { derivePath } from 'ed25519-hd-key';
const mnemonic =
"neither lonely flavor argue grass remind eye tag avocado spot unusual intact";
const seed = bip39.mnemonicToSeedSync(mnemonic, ""); // (mnemonic, password)
for (let i = 0; i < 10; i++) {
const path = `m/44'/501'/${i}'/0'`;
const keypair = Keypair.fromSeed(derivePath(path, seed.toString("hex")).key);
console.log(`${path} => ${keypair.publicKey.toBase58()}`);
}

Related

How can we open a hard drive using kernel extension in Mac OSx?

I am trying to open(access) a volume of hard drive using below code in app.
int mode=0;
int hd_h=-1;
const char* device = "/dev/rdisk1”
mode=O_RDWR|mode_basic;
hd_h = open(device, mode);
When I executed above code it returns error "Operation not permitted". Then I searched how it can be achieved and found one answer using kext we can achieve it. I created a sample kext(driver) to access harddrive in kernel space. can anybody assist how can I open volume in kext and return to user space. I have created a IOUserClient subclass and calling IOServiceOpen() in user space .
CFDictionaryRef matchingDict = NULL;
io_iterator_t iter = 0;
io_service_t service = 0;
kern_return_t kr;
// Create a matching dictionary that will find any USB device
matchingDict = IOServiceMatching("com_osxkernel_driver_IOKitTest");
// Create an iterator for all IO Registry objects that match the dictionary
kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, &iter);
if (kr != KERN_SUCCESS)
return -1;

Protobuffer API for dynamic Enum Access

I want to know how to set an Enum value dynamically.
I have the following .proto file:
syntax = "proto3";
package garden;
option go_package = "proto/garden";
message Garden {
enum Flower {
Rose = 0;
Acacia = 1;
Firethorn = 2;
Nemophila = 3;
}
Flower flower = 1;
}
One way to set the enum is the following:
garden := pb.Garden{}
garden.Flower = pb.Garden_Rose
I want to generate my garden dynamically and only have the value "Rose". There is the value mapping but the following does not work:
garden := pb.Garden{}
garden.Flower = pb.Garden_Flower_value["Rose"] // gives error: cannot use garden.Garden_Flower_value[flower] (type int32) as type garden.Garden_Flower in assignment
garden.Flower = 0 // works somehow??
I assume that I can use the protoreflect package to set the value. Unfortunately, it is not clear to me yet how it works.
garden.Flower = protoreflect.EnumNumber(pb.Garden_Rose)
Furthermore, I want to set ".Flower" dynamically. I figured out how to set fields in a struct dynamically but lack the knowledge how to cast a protoreflect.Value to a reflect.Value type.
If someone wants to know how to do all of this dynamically. I finally figured it out:
func main() {
var garden = pb.Garden{}
var gardenProto = garden.ProtoReflect()
var fields = gardenProto.Descriptor().Fields()
var flower = fields.ByName(protoreflect.Name("flower"))
var rose = protoreflect.Name("Rose")
var enumValue = protoreflect.ValueOfEnum(protoreflect.EnumNumber(flower.Enum().Values().ByName(rose).Number()))
gardenProto.Set(flower, enumValue)
fmt.Print(garden.GetFlower())
}
When changing the string "Rose" to any of the other valid Flowers the enum is automatically updated. Furthermore, make sure that the field name is the one as specified in the .proto file. In this example it was flower.
Have you already tried this approach?
flower := "Rose"
garden := pb.Garden{}
garden.Flower = pb.Garden_Flower(pb.Garden_Flower_value[flower])
fmt.Println(garden.Flower.String()) // Rose

Apps Script Exceeded MAXIMUM_RUNNING_TIME Workaround

First of all, I am continuing an old thread at this link that I am unable to comment on due to being a newbie.
I have a situation that an answer in that thread given by user Br. Sayan would really improve my Spreadsheet Google App Script. I am making calls to Google Url Shortener API, which puts quotas at 1 call per user per second. I have slowed my script down enough to accommodate this quota, but I then I run over the MAX_RUNNING_TIME for App Scripts execution due to the extended number of calls I need to make, so I need to break the loop when the execution time is exceeded and pick up where I left off.
Here is the code of his answer:
function runMe() {
var startTime= (new Date()).getTime();
//do some work here
var scriptProperties = PropertiesService.getScriptProperties();
var startRow= scriptProperties.getProperty('start_row');
for(var ii = startRow; ii <= size; ii++) {
var currTime = (new Date()).getTime();
if(currTime - startTime >= MAX_RUNNING_TIME) {
scriptProperties.setProperty("start_row", ii);
ScriptApp.newTrigger("runMe")
.timeBased()
.at(new Date(currTime+REASONABLE_TIME_TO_WAIT))
.create();
break;
} else {
doSomeWork();
}
}
//do some more work here
}
My Questions:
Is MAX_RUNNING_TIME a global variable with a value set by Apps Script that I can leave that reference as-is, or must I replace it with a value equalling the 6 minutes listed as the quota for run time on the Google API Console?
How can I place the bulk of my function within this script so that a loop that runs inside my function (say var i = 0; i < data.length; i++) will be synchronized with the loop in the portion given in the above code?
Clarification: when i is incremented up by 1, I need ii to increment by 1.
Does this happen automatically? Do I need one loop nested inside the other? Does the bulk of my function go in the first '//do some work here' or the second '//do some work here' or possibly even doSomeWork()?
#tehhowch agreed! However, HOW I need to adapt my code depends on where I need to put it in the above snippet.
Here is what I have so far:
'function short() {
var = startTime = (new Date()).getTime();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var run = 0;
var finc = 50;
var istart = run * finc;
var iLen = (run + 1) * finc;
var startRow = 2 + istart;
var endRow = startRow + finc;
var data = sheet.getSheetValues(startRow,2,endRow,1);
var shortUrl = new Array();
for (var i=istart; i < iLen; i++) {
Utilities.sleep(1100);
var url = UrlShortener.Url.insert({longUrl: data[i][0]});
shortUrl.push([url.id]);
Logger.log([url.id]);
}
var t = ss.setActiveSheet(ss.getSheets()[0]);
t.getRange(startRow,4,finc,data[0].length).clearContent();
t.getRange(startRow,4,finc,data[0].length).setValues(shortUrl);'
So if I update the code after each subsequent run to manually increase the variable 'run' by 1, and manually run the code again, this works.
I have also tried break it down into multiple functions by updating the i= and i < parts for each subsequent function, which also works, but requires much more manual work.
I have also tried, unsuccessfully, to use a prompt with a button press that continues the function, which would be better than the other attempts, but would still require a button press to resume the code after each run.
I want to automate the function as much as possible.

How to set default file browse location with firefox addon sdk

Im new Firefox addon programming.
I want set default file browse location with firefox addon sdk.
Thank you so much.
open scratchpad copy and paste this:
const nsIFilePicker = Components.interfaces.nsIFilePicker;
var fp = Components.classes["#mozilla.org/filepicker;1"]
.createInstance(nsIFilePicker);
var startDir = FileUtils.File('C:\\');
fp.displayDirectory = startDir;
fp.init(window, "Dialog Title", nsIFilePicker.modeOpen);
fp.appendFilters(nsIFilePicker.filterAll | nsIFilePicker.filterText);
var rv = fp.show();
if (rv == nsIFilePicker.returnOK || rv == nsIFilePicker.returnReplace) {
var file = fp.file;
// Get the path as string. Note that you usually won't
// need to work with the string paths.
var path = fp.file.path;
// work with returned nsILocalFile...
}
if thats what you want let me know, then ill put it in a default location

Finding DNS server settings programmatically on Mac OS X

I have some cross platform DNS client code that I use for doing end to end SMTP and on windows I can find the current DNS server ip addresses by looking in the registry. On the Mac I can probably use the SystemConfiguration framework as mentioned in the first answer, however the exact method of doing so is not immediately obvious.
For instance SCDynamicStoreCopyDHCPInfo returns some of the dynamic DHCP related data but not the DNS server addresses.
I know its very late to answer this question but may be helpful for the others.
This Code will help out for this task ..
SCPreferencesRef prefsDNS = SCPreferencesCreate(NULL, CFSTR("DNSSETTING"), NULL);
CFArrayRef services = SCNetworkServiceCopyAll(prefsDNS);
long servicesCount = CFArrayGetCount(services);
for (long i = 0; i < servicesCount; i++) {
const SCNetworkServiceRef service = (const SCNetworkServiceRef)CFArrayGetValueAtIndex(services, i);
CFStringRef interfaceServiceID = SCNetworkServiceGetServiceID(service);
CFStringRef primaryservicepath = CFStringCreateWithFormat(NULL,NULL,CFSTR("State:/Network/Service/%#/DNS"),interfaceServiceID);
SCDynamicStoreRef dynRef = SCDynamicStoreCreate(kCFAllocatorSystemDefault, CFSTR("DNSSETTING"), NULL, NULL);
CFPropertyListRef propList = SCDynamicStoreCopyValue(dynRef,primaryservicepath);
if (propList) {
CFDictionaryRef dict = (CFDictionaryRef)propList;
CFArrayRef addresses = (CFArrayRef)CFDictionaryGetValue(dict, CFSTR("ServerAddresses"));
long addressesCount = CFArrayGetCount(addresses);
for (long j = 0; j < addressesCount; j++) {
CFStringRef address = (CFStringRef)CFArrayGetValueAtIndex(addresses, j);
// Print address
CFShow(address);
}
CFRelease(propList);
}
CFRelease(dynRef);
CFRelease(primaryservicepath);
}
CFRelease(services);
CFRelease(prefsDNS);
I know it's been a long time since you needed this, but there is nothing worse than a old unsolved answer. You can't access them from "/etc/resolv.conf" because of permission issues. After much searching, and a little luck I discovered you can get it via res_ninit() function.
// Get native iOS System Resolvers
res_ninit(&_res);
res_state res = &_res;
for (int i = 0; i < res->nscount; i++) {
sa_family_t family = res->nsaddr_list[i].sin_family;
int port = ntohs(res->nsaddr_list[i].sin_port);
if (family == AF_INET) { // IPV4 address
char str[INET_ADDRSTRLEN]; // String representation of address
inet_ntop(AF_INET, & (res->nsaddr_list[i].sin_addr.s_addr), str, INET_ADDRSTRLEN);
} else if (family == AF_INET6) { // IPV6 address
char str[INET6_ADDRSTRLEN]; // String representation of address
inet_ntop(AF_INET6, &(res->nsaddr_list [i].sin_addr.s_addr), str, INET6_ADDRSTRLEN);
}
}
res_ndestroy(res);
You can use the SystemConfiguration framework. It's in C.
Update: apparently the rest of the web is harder to use than I thought. Search for the key "State:/Network/Service/ServiceID/DNS" where ServiceID is the ID of the service.
They are also available from
/etc/resolv.conf
You could read from /etc/resolv.conf.

Resources