while writing a Chaincode (Hyperledger-fabric) in Golang I am confused while fallowing documentation - blockchain

I am confused ,when I am following fabric-samples (asset-transfer-basic --->https://github.com/hyperledger/fabric-samples/blob/main/asset-transfer-basic/chaincode-go/chaincode/smartcontract.go) for writing smart contract in Golang , the methods takes ctx contractapi.transcationcontextinterface as there function parameter , but when I am trying to refer other chaincode's on internet every one else are taking stub shim.chaincodesubinterface as there function parameter , if I use stub as my function parameter then how can I make use of clientidenty methods (cid package) , and in asset-transfer-basic code Init/Invoke are not mentioned also in main function when creating a new chaincode ( assetChaincode, err := contractapi.NewChaincode(&SmartContract{}) ) SmartContract{} does not implement contractinterface . I am try to do a project on ERC20 token for applying for jobs so please help

The examples you have found that include an Init and Invoke function, and take ChaincodeStubInterface as a parameter are using the older and lower-level fabric-chaincode-go API directly. The asset-transfer-basic sample is using the newer and higher-level fabric-contract-api-go API. This is built on top of the lower-level API and allows you access to all the same information as the lower-level API (note that the transaction context passed into transaction functions using the higher-level API has a GetStub method to obtain the corresponding low-level ChaincodeStubInterface).
I would recommend using the Contract API as demonstrated by the asset-transfer samples. The two approaches are functionally equivalent but the Contract API provides a cleaner abstraction requiring less boiler-plate code.

Related

Web Service authorization issue

Need some help with KDSoap 1.7 or gSOAP
I'm trying to use some Web Service API: http://sparkgatetest.interfax.ru/iFaxWebService/ . There is list of methods and to interact with them u must:
call Authmethod
call any method u need to
call End
Problem is, this is HTTP protocol, so if you used Authmothod succesfully, and after that trying to call methods which return some information, u got an "Authorization error" message in xml response.
So, to correct usage of this API u should call three methods (Authmethod, some method, End) in one request. How should I do it with KDSoap/gSOAP?
p.s. i found setAuthentication function in client interface, but it takes KDSoapAuthentication class as argument, maybe there is a way to customize it? And End method also a big problem aswell.

AWS Lambda NodeJS locale/variable isolation

There is a concern about potential problem with reusable variables in aws-lambda.
A user's locale is passed as
Browser cookies => AWS API Gateway => Lambda (NodeJS 6.10)
On the server side localization is implemented with a static variable in a class. Presenting typescript code for clarity but can be done in pure ECMAScript.
Module Language.ts
export default class Language
{
public static Current: LanguageCode = LanguageCode.es;
}
Static Language.Current variable is used across different parts of the application for manual localization and it works perfectly on the client side (react + redux).
Lambda function
import {APIGatewayEvent, Context, Callback} from 'aws-lambda';
import Language from './pathToModule/Language.ts';
export const api = function(event: APIGatewayEvent, context: Context, callback: Callback)
{
Language.Current = event.headers.cookie.locale;
// do the logic here
}
Potential problem
According to AWS documentation NodeJS instances can be reused for different requests. It means that famous concurrent problems have to be considered, e.g.
User 1 calls lambda function. The locale is set to English.
In parallel user 2 calls the same lambda instance. The local is changed to Spanish.
User 1 code continues and reads modified (wrong) locale variable from the shared module Language.
How do you resolve this problem?
For convenience it is good to have only one place for locale change. As I understand the same concern exists for all famous i18n npm packages (i18next, i18n, yahoo i18n, etc).
One of the best practices for Lambda functions is to try and not write code which maintains state.
Here you are initializing the locale based on an initial request and applying it to all future requests, which is inherently flawed even on server based code, forget server less.
To fix this, you will need to initialize the localization library for each request, or at least maintain an in memory lazy map, which you can make use of use the current request's locale to achieve the desired localization.
There are several solutions:
Node JS container is reused only after a function process is finished (callback or error is occurred) (thanks to #idbehold). Thus there is always a unique context per a function call.
Refactor code and pass a locale variable back and force (#Yeshodhan Kulkarni suggestion).
For example, return a function as an intermediate result and use it before calling the result back.
var localizableResult = ...;
var result = localizableResult.Localize(requestedLocale).
If there is a need to use a local stack (kind of a thread context) for other projects there is a npm package node-continuation-local-storage.
Case 1 makes it really simple to use global variables for current locale.

webrtc - GetStats() call OnStatsDelivered with an empty RTCStatsReport

I'm using new WebRTC stats API with RTCStatsCollectorCallback object that is called when stats report is generated. I'm invoke GetStats() and then I can see that OnStatsDelivered is called with a RTCStatsReport that contains just one (empty) item in stats_ member. In GetStats() call I pass my own implementation of RTCStatsCollectorCallback that implements webrtc::RTCStatsCollectorCallback interface. My question is, is neccessary some setup or constraints in PeerConnection in order to get RTCStatsReport with the metrics? I mean, to get, for example kStatsValueNameRtt stat, I need to set something in PeerConnection. Note that I'm using C++ native API in branch 55. Is this new stats API full implemented?
I've used the older GetStats method with success:
bool GetStats(StatsObserver* observer,
webrtc::MediaStreamTrackInterface* track,
StatsOutputLevel level) override;
It could be your problem was due to trying to use an in-progress API (webrtc framework is a bit wild west). Currently, peerconnectiointernface.h says the following:
// Gets stats using the new stats collection API, see webrtc/api/stats/. These
// will replace old stats collection API when the new API has matured enough.
// TODO(hbos): Default implementation that does nothing only exists as to not
// break third party projects. As soon as they have been updated this should
// be changed to "= 0;".
virtual void GetStats(RTCStatsCollectorCallback* callback) {}
As I'm writing this response, your question is 6 months old, so it's possible the this new API is now working (though the comment above suggests otherwise).

How do I use Oauth with C++ ?? Etrade API

I am having problems with oauth. Let me start by saying that I have only been studying C++ for about a month. I am working on a Etrade API application. I have been struggling with this for a few weeks. Ok Etrade has provided the header, DLL and library files. I am having trouble just calling a simple function. Etrade list examples on how to call a Function for Java, and PHP but no C++. I just need a example for one function and I can pretty much go from there. here is a link to the API help
https://us.etrade.com/ctnt/dev-portal/getContent?contentUri=V0_Code-SDKGuides-VC
the arguments for the first function are
m_environment IN Optional. Possible values are SANDBOX (default) and LIVE.
m_strConsumerKey IN OAuth consumer key provided by E*TRADE
m_strConsumerSecret IN OAuth consumer secret provided by E*TRADE
m_strToken OUT Returned by the function if successful
m_strTokenSecret OUT Returned by the function if successful
m_strCallback IN Optional; default value is "oob"
Here is my code first function (oauth)
int main(int argc, char **argv)
{
}
bool COAuthSDK::GetRequestToken(CClientDetails &objClientDetails)
{
return GetRequestToken;
}
You're missing the point. ETrade provides you with COAuthSDK::GetRequestToken; You're supposed to call it, not re-implement it yourself. The m_ arguments are members of the CClientDetails object that you, as the client, have to provide.
Just a heads up. The Authorize URL in the docs(v0) is wrong! Doh! If you are having problems with that step, try the following URL.
Here is the correct URL: https://us.etrade.com/e/t/etws/authorize
Notice there is an additional 't' in the URL
BTW, I wrote a simple Node app called Trading Robo Monkey. If you have never used OAuth before, you can try to see if that was your problem by looking at the JS code
https://github.com/shikhirsingh/ETrade-API-Robo-Trading-Monkey-4-NodeJS

SOAP Webservice error - design practice

I need to design a SOAP api (my first one!). What are the best practices regarding errors returned to the caller.
Assuming an api as follow
[WebMethod]
public List<someClass> GetList(String param1)
{
}
Should I
Throw an exception. Let the SOAP infrastructure generate a SOAP fault -- and the caller would have to try/catch. This is not very explanatory to the caller
Have the return parameter be a XMLDOcument of some sort, with the first element being a return value and then the List.
Looking at the return SOAP packet I see that the response generated looks like the following
<GetListResponse>
<GetListResult>
...
...
</GetListResult>
</GetListResponse>
Can we somehow change the return packet so that the "GetListResult" element is changed to "GetListError" in case of error
Any other way?
Thanks!
Probably the most appropriate SOA pattern to follow would be a Fault Contract, which is essentially a Data Contract that is wrapped in the SOAPException.
I am posting examples in .NET, since it looks like that is what you are using (and that is what I know :) )
In WCF, you can define a DataContract, then decorate your OperationContract interface with a a "FaultContract" attribute that specifies it as the return value:
public partial interface MyServiceContract
{
[System.ServiceModel.FaultContract(typeof(MyService.FaultContracts.ErrorMessageFaultContract))]
[System.ServiceModel.OperationContract(...)]
ResponseMessage SOAMethod(RequestMessage request) {...}
}
For ASMX web services, (as it appears you are using from your code snippet), you can't use this attribute or setup. So to implement the pattern, you would need to:
Define a serializable class to hold your exception information (i.e. ErrorData)
When an exception is thrown in your service, catch it and in your error handling code, add the info to the ErrorData class
Append the serialized ErrorData class to a SoapException class:
SoapException mySoapException = new SoapException(message, SoapException.ServerFaultCode, "", serialzedErrorDataClass);
Throw the SoapException in your code
On your client side, you will need to deserialize the message to interpret it.
Kind of seems like a lot of work, but this way you have total control of what data gets returned. Incidentally, this is the pattern that is used by the ServiceFactory from Microsoft patterns & practices for ASMX web services.
There is some good information on Coding Horror.
You can cause the correct fault to be returned from old ASMX services, but it's not easy. First of all, you'll have to hand-code the WSDL, because the ASMX infrastructure will never create Fault elements in a WSDL. Then, you have to serialize the desired fault data into an XmlElement that you will then provide as the Detail property of the SoapException that you will throw.
It's much easier with WCF. You can declare a number of FaultContracts for each operation, and WCF will generate the correct WSDL to refer to them. You then simply throw a FaultException, where type T is the type of the FaultContract. Pass the T instance to the constructor, and you're all set.
I can't give you specifies for .net (which seems to be what you're asking), but SOAP provides a mechanism for expressing strongly-typed exceptions. The SOAP fault element can have an optional FaultDetail sub-element, and this can contain arbitrary XML documents, such as your GetListError. These document types should be defined in the WSDL as a wsdl:fault inside the wsdl:operation
The trick is persuading the web service stack to turn an exception (which is the "correct" way of writing your business logic) into a properly marshalled fault detail. And I can't help you with that bit.